paulgorman.org/technical

Rust

============================================================================

Install Rust:

$ curl -f -L https://sh.rustup.rs -O
$ sh rustup.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.