(2018)
Read the free book The Rust Programming Language.
Install Rust:
$ curl https://sh.rustup.rs -sSf | sh
Hello, world:
π $ mkdir -p /tmp/rusthello
π $ cd /tmp/rusthello
π $ cat << 'EOF' > main.rs
fn main() {
println!("Hello, world");
}
EOF
π $ rustc main.rs
π $ ./main
Hello, world
The exclamation mark in println!()
indicates that it’s a macro rather than a function.
Cargo is Rustβs build system and package manager. Cargo build our code, downloads dependencies/libraries, and builds dependencies. Change rusthello to use Cargo:
π $ mkdir -p ~/tmp/rusthello/src
π $ cd ~/tmp/rusthello/
π $ mv main.rs src/
π $ rm ./main
π $ cat << 'EOF' > Cargo.toml
[package]
name = "rusthello"
version = "0.0.1"
authors = [ "My Name <me@example.com>" ]
EOF
π $ cargo build
π $ ./target/debug/rusthello
Hello, world
The build and run step can be combined with:
π $ cargo run
Hello, world
Do an optimized build for release:
π $ cargo build --release
Cargo can set up necessary directories and files for a new project (including initializing it as a Git repo) like:
π $ cargo new myproject --bin
Mutable and immutable bindings (i.e. “variables):
let foo = 5; // `foo` is immutable.
let mut bar = 5; // `bar` is mutable.