Installation
Installing rustup first…
install rustup via shell script
curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
install rustup via brew
brew install rustup-init (1)
rustup-init (2)
Welcome to Rust!
[...]
Current installation options:
default host triple: aarch64-apple-darwin
default toolchain: stable (default)
profile: default
modify PATH variable: yes
1) Proceed with standard installation (default - just press enter)
2) Customize installation
3) Cancel installation
| 1 | install rustup |
| 2 | install rust binaries and add them to paths etc… |
verify the installation
rustc --version (1)
cargo --version (2)
rustup --version (3)
| 1 | version of the Rust compiler |
| 2 | version of the Cargo build tool and package manager |
| 3 | version of the Rust toolchain installer |
keep your toolchain up to date
rustup update (1)
rustup self update (2)
| 1 | update all installed toolchains |
| 2 | update rustup itself |
Toolchains and Components
Managing toolchains, targets and helper components…
manage toolchains
rustup toolchain list (1)
rustup toolchain install nightly (2)
rustup default stable (3)
rustup override set nightly (4)
| 1 | list installed toolchains |
| 2 | install the nightly toolchain |
| 3 | set stable as the global default |
| 4 | use nightly for the current directory only |
add components and cross-compilation targets
rustup component add clippy rustfmt (1)
rustup component add rust-analyzer (2)
rustup target add wasm32-unknown-unknown (3)
| 1 | add the linter (clippy) and formatter (rustfmt) |
| 2 | add the language server used by most editors |
| 3 | add a target to cross-compile, e.g. to WebAssembly |
Cargo
Cargo is Rust’s build tool and package manager…
create a new project
cargo new my_app (1)
cargo new my_lib --lib (2)
cargo init (3)
| 1 | create a new binary (application) project |
| 2 | create a new library project |
| 3 | initialize a project in the current directory |
build, run and test
cargo build (1)
cargo build --release (2)
cargo run (3)
cargo run -- --arg1 value (4)
cargo test (5)
cargo check (6)
| 1 | compile in debug mode (fast build, unoptimized) |
| 2 | compile optimized for production into target/release |
| 3 | build and run the project |
| 4 | pass arguments after -- to your program |
| 5 | run all unit and integration tests |
| 6 | type-check without producing a binary (very fast) |
manage dependencies
cargo add serde --features derive (1)
cargo add tokio@1 (2)
cargo remove serde (3)
cargo update (4)
cargo tree (5)
| 1 | add a dependency and enable one of its features |
| 2 | add a dependency pinned to a major version |
| 3 | remove a dependency |
| 4 | update dependencies within the allowed version ranges |
| 5 | show the dependency tree |
Formatting and Linting
Keep your code clean and idiomatic…
format and lint
cargo fmt (1)
cargo fmt --check (2)
cargo clippy (3)
cargo clippy -- -D warnings (4)
| 1 | format the whole project with rustfmt |
| 2 | check formatting without changing files (useful in CI) |
| 3 | run the clippy linter for common mistakes and idioms |
| 4 | treat lint warnings as errors (fail the build on warnings) |
Hello World
A first program…
src/main.rs
fn main() { (1)
println!("Hello, world!"); (2)
}
| 1 | main is the entry point of every executable |
| 2 | println! is a macro (note the !) that prints a line to stdout |
Variables and Mutability
Bindings are immutable by default…
let bindings
let x = 5; (1)
let mut y = 10; (2)
y += 1;
const MAX_POINTS: u32 = 100_000; (3)
let x = x + 1; (4)
| 1 | immutable binding; reassigning x would not compile |
| 2 | mut makes the binding mutable |
| 3 | const must be typed and is evaluated at compile time |
| 4 | shadowing: a new x reuses the name, even with a new type |
Ownership, Borrowing and References
Ownership is Rust’s most distinctive feature and how it guarantees memory safety without a garbage collector…
move, borrow and mutable borrow
let s1 = String::from("hello");
let s2 = s1; (1)
let s3 = String::from("world");
let len = calc_len(&s3); (2)
println!("{s3} has length {len}");
let mut s4 = String::from("foo");
add_bar(&mut s4); (3)
fn calc_len(s: &String) -> usize {
s.len()
}
fn add_bar(s: &mut String) {
s.push_str("bar");
}
| 1 | ownership moves from s1 to s2; s1 is no longer usable |
| 2 | &s3 borrows immutably; the caller keeps ownership |
| 3 | &mut s4 borrows mutably; only one mutable borrow may exist at a time |
Error Handling
Rust models recoverable errors with Result and absence with Option instead of exceptions or null…
Option, Result and the ? operator
use std::num::ParseIntError;
fn first_char(s: &str) -> Option<char> { (1)
s.chars().next()
}
fn parse(s: &str) -> Result<i32, ParseIntError> { (2)
let n: i32 = s.parse()?; (3)
Ok(n * 2)
}
fn main() {
match parse("21") { (4)
Ok(n) => println!("got {n}"),
Err(e) => println!("error: {e}"),
}
}
| 1 | Option<T> is Some(value) or None |
| 2 | Result<T, E> is Ok(value) or Err(error) |
| 3 | ? returns early with the error if parsing fails |
| 4 | match forces you to handle every case exhaustively |
Structs, Enums and Pattern Matching
Model data with struct and enum, then destructure it with match…
structs, enums and match
struct Point { (1)
x: i32,
y: i32,
}
enum Shape { (2)
Circle(f64),
Rectangle(f64, f64),
}
fn area(shape: &Shape) -> f64 {
match shape { (3)
Shape::Circle(r) => std::f64::consts::PI * r * r,
Shape::Rectangle(w, h) => w * h,
}
}
| 1 | a struct groups named fields |
| 2 | an enum variant can carry data |
| 3 | match destructures the variant and binds its data |
Testing
Tests live next to the code and run with cargo test…
unit tests
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)] (1)
mod tests {
use super::*;
#[test] (2)
fn adds_two_numbers() {
assert_eq!(add(2, 3), 5); (3)
}
}
| 1 | the tests module is only compiled when testing |
| 2 | #[test] marks a function as a test case |
| 3 | assert_eq! fails the test if the values differ |