Introduction
Getting Started · Rust 1
What Rust Is
Rust is a compiled, statically typed language that is as fast as C++ and refuses to compile programs with memory bugs. Its big idea is ownership: every value has exactly one owner, and the compiler checks how it is used, so there are no null pointer crashes, no dangling references and no data races, without a garbage collector. Expect to argue with the compiler at first; it is usually right.
- rustup from rustup.rs installs
rustc(the compiler),cargo(the build tool and package manager) and keeps them updated. Check withcargo --version. - An editor: VS Code with the rust-analyzer extension, which shows types and errors as you type.
- Cargo — builds, runs, tests and fetches libraries (crates); you almost never call
rustcyourself - Ownership — the rules about who holds a value and who may borrow it
- Borrow checker — the part of the compiler that enforces them
Your First Program
Create and run a project
cargo new hello # makes a folder with Cargo.toml and src/main.rs
cd hello
cargo run # compiles and runssrc/main.rs
// My first Rust program
fn main() {
println!("Hello, World!");
} Compiling hello v0.1.0
Finished dev [unoptimized + debuginfo] target(s)
Running `target/debug/hello`
Hello, World!Read it
fn main()is where the program starts. Every program has exactly one.println!ends in!because it is a macro, not a function; it checks the format string at compile time.- Blocks use braces; statements end with semicolons; indentation is four spaces by convention, and
cargo fmtwill fix it for you. cargo runrebuilds only when something changed.cargo build --releasemakes the fast version.
More printing
let name = "Max";
let age = 30;
println!("{} is {}", name, age); // positional
println!("{name} is {age}"); // named: variables in the braces
println!("{:.2}", 3.14159); // 3.14
println!("{:>8}|{:<8}|", "right", "left"); // padding and alignment
println!("{:?}", vec![1, 2, 3]); // {:?} debug-prints almost anything: [1, 2, 3]
print!("no newline ");
eprintln!("to the error stream");Comments, Style and the Compiler
Comments
// One line, to the end of the line
/* Several lines,
between the markers */
/// A documentation comment, in Markdown, above a function or type.
/// `cargo doc --open` turns these into a website.
fn cube(x: f64) -> f64 { x * x * x }Conventions
- Variables and functions in snake_case:
total_score,print_balance - Types, structs, enums and traits in UpperCamelCase:
BankAccount - Constants in ALL_CAPS:
const MAX_SIZE: usize = 100; - The compiler warns about unused variables and non-snake-case names. Fix warnings; they are usually real.
cargo fmtformats;cargo clippysuggests idiomatic rewrites. Run both before handing anything in.
| Kind of error | When it shows up | Example |
|---|---|---|
| Compile-time error | When you build; nothing runs until it is fixed. The message names the line and usually says how to fix it | A type mismatch, using a moved value, a missing semicolon, borrowing something twice |
| Panic (run-time) | While running; the program prints a message and stops | Indexing past the end of a Vec, unwrap() on a None, integer overflow in debug builds, division by zero |
| Logic error | Never announced; the program runs and gives the wrong answer | Integer division where you meant a decimal, an off-by-one in a range |
Read the whole compiler message. Rust’s errors are long because they explain. The first line says what is wrong, the arrows show where, and a help: line often contains the exact fix. rustc --explain E0382 gives a page on any error code.
Compile errors you will meet in the first week
| Code and first line | What you did | Fix |
|---|---|---|
E0308: mismatched types … expected `f64`, found `()` | Put a semicolon after the last expression of a function body, so it returned nothing | Remove the semicolon; the help: line says exactly that |
E0277: cannot add a float to an integer, cannot add `i64` to `i32`, cannot divide `{float}` by `{integer}` | Mixed number types in one expression | Convert one side: count as f64 |
E0384: cannot assign twice to immutable variable `x` | Changed a variable declared with plain let | let mut x |
E0425: cannot find function `cube_volume` in this scope | Misspelled a name, or called a function you have not written yet | Check the spelling and the fn |
E0433: cannot find type `HashMap` in this scope | Used a library type without importing it | use std::collections::HashMap; at the top |
E0369: cannot add `&str` to `&str` | "a" + "b" | format!("{a}{b}"), or make the left side a String |
E0004: non-exhaustive patterns | A match that misses a case | Add the arm or _ => |
E0382: borrow of moved value | Used a String or Vec after handing it to something else | See Functions, Ownership and Borrowing |
The code after error[...] is stable across Rust versions even when the wording changes, so it is the thing to search for. The warnings about unused variables are not errors; the program still ran.
Programming with Numbers and Strings
Getting Started · Rust 1
Variables and Types
Variables are immutable by default: once set, they cannot change unless you say mut. Every value has a type fixed at compile time; the compiler infers most of them, so you write a type only when it cannot tell or when you want to be explicit.
let cans_per_pack = 6; // i32 by default
let mut count = 0; // mut: may be changed later
count += 1;
let can_volume = 0.335; // f64 by default
let done = false; // bool
let grade = 'A'; // char: a single Unicode character, in single quotes
let name = "Harry"; // &str: a string slice (text baked into the program)
let owned = String::from("Harry"); // String: growable, owned text
const MAX_SIZE: usize = 100; // a constant: type required, ALL_CAPS
let big: u64 = 10_000_000_000; // an explicit type; underscores for readability
cans_per_pack = 7; // error: cannot assign twice to immutable variable
let cans_per_pack = 7; // but SHADOWING with a new let is fine, even with a new type| Type | Holds | Notes |
|---|---|---|
i32, i64, i8, i16, i128 | Signed whole numbers of that many bits | i32 is the default; overflow panics in debug builds and wraps in release |
u32, u64, u8 … | Unsigned whole numbers | u8 is a byte |
usize / isize | The size of a pointer (64 bits on your machine) | Every index and length is a usize |
f64, f32 | Decimal numbers | f64 is the default; 0.1 + 0.2 == 0.3 is false |
bool | true or false | The only thing an if accepts: no truthy numbers |
char | One Unicode scalar, 4 bytes | 'a', 'é', '🦀' |
&str and String | Text | See Strings below; the two-string system is the first Rust hurdle |
() | The unit type: “nothing” | What a function with no return value returns |
Arithmetic
| Operator | Meaning | Example |
|---|---|---|
+ - * | Add, subtract, multiply | 7 * 3 → 21 |
/ | Division. Integer ÷ integer drops the fraction; float ÷ float is exact | 7 / 2 → 3; 7.0 / 2.0 → 3.5 |
% | Remainder | 7 % 2 → 1; n % 2 == 0 tests for even |
+= -= *= /= | Combine and assign | total += price;. There is no ++ |
as | Convert between number types | x as f64, y as i32, n as usize |
let minutes = 135;
let hours = minutes / 60; // 2
let left = minutes % 60; // 15
let r = 2.0_f64.sqrt(); // 1.4142135623730951 (methods on numbers)
let area = std::f64::consts::PI * 3.0_f64.powi(2);
let whole = 19.99_f64 as i32; // 19: as truncates
let nearest = 19.99_f64.round() as i32; // 20
let two_dp = (3.14159_f64 * 100.0).round() / 100.0; // 3.14 (or format with {:.2})
let bigger = 3.max(9); // 9
let dist = (-4.5_f64).abs(); // 4.5
let avg = sum as f64 / count as f64; // convert BOTH before dividing
// no implicit conversions, even between int sizes:
let a: i32 = 5;
let b: i64 = 10;
let c = a as i64 + b; // a + b alone is a type errorRust never converts numbers for you. 5 + 2.0 is an error, i32 + i64 is an error, and an f64 cannot index a Vec. Convert with as (or .into() for widening) and the error goes away. The upside: no silent precision loss, ever.
Strings: &str and String
Rust has two string types. &str is a borrowed slice of text, usually a literal or a view into a String. String is owned, growable text on the heap. You build and modify a String; you pass around &str. A &String turns into a &str automatically, so functions should take &str.
let mut greeting = String::from("Hello"); // or "Hello".to_string()
let n = greeting.len(); // 5: BYTES, not characters
greeting.push_str(", World"); // append text
greeting.push('!'); // append a char
let loud = greeting.to_uppercase(); // a new String
let both = format!("{} and {}", greeting, loud); // format! builds a String
let part = &greeting[1..3]; // "el": a &str slice by BYTE range (panics mid-character)
let where_l = greeting.find('l'); // Some(2), or None
let same = greeting == "Hello, World!"; // compares content
let inside = greeting.contains("World"); // true
let first = greeting.chars().next(); // Some('H'): indexing greeting[0] is NOT allowed
for ch in greeting.chars() { print!("{ch} "); }Useful string methods
| Method | Does |
|---|---|
s.trim() | A &str without surrounding whitespace (what read_line leaves on) |
s.to_lowercase(), s.to_uppercase() | New Strings |
s.replace("a", "b") | A new String with every a replaced |
s.split(','), s.split_whitespace() | An iterator of pieces; .collect::<Vec<_>>() to get a Vec |
parts.join(", ") | Glue a Vec of strings together |
s.starts_with("Dr"), s.is_empty() | Tests |
s.chars().count() | Number of characters (vs len() bytes) |
s.chars().rev().collect::<String>() | Reversed |
Converting
let count: i32 = "42".parse().unwrap(); // parse needs the target type
let price = "3.95".parse::<f64>().unwrap(); // turbofish form
let bad = "abc".parse::<i32>(); // Err(...): parse returns a Result
let text = 42.to_string(); // "42"
let s = format!("{}", 42); // the same
let joined = "Total: ".to_string() + &text; // String + &str works; &str + &str does not.unwrap() says “I am sure this worked; panic if not.” Fine while learning and in examples. Files and Exceptions shows how to handle the Err properly.
Input and Formatted Output
src/main.rs
use std::io;
fn main() {
println!("Please enter the number of bottles:");
let mut line = String::new();
io::stdin().read_line(&mut line).expect("failed to read"); // appends to line, newline included
let bottles: i32 = line.trim().parse().expect("not a whole number");
println!("Price per bottle:");
line.clear(); // reuse the buffer
io::stdin().read_line(&mut line).expect("failed to read");
let price: f64 = line.trim().parse().expect("not a number");
let total = bottles as f64 * price;
println!("Total: ${total:.2} for {bottles} bottles");
}Please enter the number of bottles:
3
Price per bottle:
1.5
Total: $4.50 for 3 bottles| Inside the braces | Meaning | Example |
|---|---|---|
{} | Display: for people | println!("{}", x) |
{:?} | Debug: for programmers; works on Vec, tuples, Option, your structs with #[derive(Debug)] | {:#?} pretty-prints across lines |
{:.2} | Float with 2 decimals | 3.50 |
{:8.2}, {:>8}, {:<8}, {:^8} | Width and alignment | Right is the default for numbers, left for text |
{:05} | Zero-padded | 00042 |
{:x}, {:b} | Hex, binary | {:#x} adds 0x |
read_line appends to the String you give it and keeps the newline, so the pattern is always clear(), read_line(&mut line), trim(), parse(). The &mut says the function may change your String; that is the first borrow you will write.
Decisions
Control Flow · Rust 1
The if Expression
if floor > 13 {
actual_floor = floor - 1;
} else if floor == 13 {
println!("There is no 13th floor.");
} else {
actual_floor = floor;
}
// if is an EXPRESSION: it produces a value, so this replaces the ? : operator
let label = if n % 2 == 0 { "even" } else { "odd" };| Rust | Math | Note |
|---|---|---|
> >= | > ≥ | |
< <= | < ≤ | |
== | = | Two equals signs. if x = 5 is a compile error, as it should be |
!= | ≠ | |
(1..=10).contains(&x) | 1 ≤ x ≤ 10 | Range tests |
| Operator | True when |
|---|---|
a && b | both are true (and) |
a || b | at least one is true (or) |
!a | a is false (not) |
&& and || short-circuit: in x != 0 && 1 / x > 2 the division is skipped when x is 0.
Only Booleans, No Parentheses, Braces Always
- The condition is a
bool, nothing else.if count { ... }with an integer is a compile error; writeif count != 0. There is no truthiness. - No parentheses around the condition (the compiler warns if you add them); braces around the body always, even for one line.
- Both branches of an
ifused as a value must have the same type:if ok { 1 } else { "no" }is an error. - Strings compare by content with
==, Strings and &strs alike:if word == "quit",if word.eq_ignore_ascii_case("quit"),if word < other(by bytes). - Floats: compare with a tolerance,
(x - y).abs() < 1e-12. There is noNaNsurprise in integers because there is no integer NaN.
Ranges, as an expression
// Letter grade: each test assumes the earlier ones failed
let grade = if score >= 90 {
"A"
} else if score >= 80 {
"B"
} else if score >= 70 {
"C"
} else {
"F"
};match: The Switch That Checks Everything
match compares a value against patterns and runs the first arm that fits. The compiler insists the arms cover every possible value, so you cannot forget a case. It is the workhorse of Rust: every Option and Result is taken apart with it.
Values and ranges
let name = match digit {
1 => "one",
2 | 3 => "two or three", // or
4..=9 => "several", // inclusive range
_ => "many", // _ matches anything else: required unless every value is covered
};
match (x > 0, y > 0) { // match on a tuple
(true, true) => println!("first quadrant"),
(false, true) => println!("second"),
_ => println!("below the axis"),
}Option: a value that might be missing
let found: Option<usize> = names.iter().position(|n| n == "Bob");
match found {
Some(i) => println!("Bob is at {i}"), // i is bound to the value inside
None => println!("No Bob"),
}
// when you only care about one arm:
if let Some(i) = found {
println!("Bob is at {i}");
}
// Option has helpers too:
let i = found.unwrap_or(0); // 0 if None
let doubled = found.map(|i| i * 2); // Option<usize>| Pattern | Matches | Example |
|---|---|---|
5, "quit", 'a' | That exact value | 1 => ... |
a | b | Either | 'a' | 'e' | 'i' => ... |
1..=9 | An inclusive range | |
Some(x), None, Ok(v), Err(e) | The variants of Option and Result, binding what is inside | |
x if x > 100 | A binding with a guard | n if n % 2 == 0 => "even" |
_ | Anything, ignored | The catch-all arm |
“non-exhaustive patterns” is the compiler telling you a match misses a case. Add the arm or a _ => catch-all. This is the error that replaces a whole class of bugs in other languages.
// the first match above, with the _ arm deleted and digit an i32:
error[E0004]: non-exhaustive patterns: `i32::MIN..=0_i32` and `10_i32..=i32::MAX` not covered
= note: the matched value is of type `i32`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard patternThe message lists exactly which values nobody handles. For an Option it says `None` not covered; for your own enum it names the missing variant. A match on an integer almost always needs the _ arm; a match on an enum usually should not have one, so that adding a variant later makes every forgotten match fail to compile.
Loops
Control Flow · Rust 1
The Three Loops
| Loop | Use it when | Shape |
|---|---|---|
loop | Repeat until a break; can return a value | loop { ... if done { break; } } |
while | You do not know how many times; stop when a condition changes | while balance < target { ... } |
for | Each element of a range or collection; the only counting loop you need | for i in 0..10 { ... }, for v in &values { ... } |
// while: years until the balance doubles
let mut year = 0;
while balance < 2.0 * initial {
year += 1;
balance += balance * RATE / 100.0;
}
// for over a range: 1 to 10 inclusive
for i in 1..=10 {
println!("{i} squared is {}", i * i);
}
// for over a collection, borrowing it so it can be used afterwards
for v in &values {
total += v;
}
// loop with break: at least once, and it can hand back a value
let value = loop {
let v = read_number();
if v > 0 {
break v; // the loop's value
}
println!("Please enter a positive number.");
};| Range | Produces | Note |
|---|---|---|
0..5 | 0, 1, 2, 3, 4 | Two dots exclude the end |
1..=5 | 1, 2, 3, 4, 5 | ..= includes it |
(0..10).step_by(2) | 0, 2, 4, 6, 8 | |
(1..=10).rev() | 10 down to 1 | There is no negative step; reverse instead |
0..values.len() | Every valid index | Only when you need the index: see enumerate |
Common Loop Algorithms
Sum, average, count
let mut total = 0.0;
let mut count = 0;
for line in input.lines() {
if let Ok(v) = line.trim().parse::<f64>() { // skip lines that are not numbers
total += v;
count += 1;
}
}
let average = if count > 0 { total / count as f64 } else { 0.0 };// with input = "10\n20\nabc\n\n30\n": count = 3, total = 60, average = 20
// the lines "abc" and "" fail to parse, so the if let skips themThe same three parts as in every language: set up before (let mut total, let mut count), update inside, use after. Two Rust details: both accumulators need mut, and count as f64 is required because total / count with an integer count is E0277: cannot divide `{float}` by `{integer}`. The if count > 0 guard avoids 0.0 / 0.0, which is NaN, not a panic.
Maximum and minimum
let mut largest = values[0];
for &v in &values { // &v: copy the number out of the reference
if v > largest {
largest = v;
}
}
// or let the library do it:
let largest = *values.iter().max().unwrap(); // integers
let largest = values.iter().cloned().fold(f64::MIN, f64::max); // floats have no max() because of NaNSentinel value
let mut sum = 0.0;
loop {
let salary = read_number(); // your helper; -1.0 means finished
if salary == -1.0 {
break;
}
sum += salary;
}Finding the first match
let mut position = None;
for (i, v) in values.iter().enumerate() {
if *v == target {
position = Some(i);
break;
}
}
// or: let position = values.iter().position(|&v| v == target);Iterators: Where Rust Loops Really Live
A for loop consumes an iterator. Collections give you three: iter() borrows each element (&T), iter_mut() borrows mutably, into_iter() moves the elements out. Iterator adapters such as map, filter and enumerate chain together, and nothing runs until a for or a consumer like sum or collect pulls the values through.
Index and value together
for (i, name) in names.iter().enumerate() {
println!("{}. {}", i + 1, name);
}
for (name, score) in names.iter().zip(scores.iter()) { // two collections in step
println!("{name}: {score}");
}
for v in values.iter_mut() { // change each element in place
*v *= 2;
}Nested loops: a table
for row in 1..=3 {
for col in 1..=4 {
print!("{:4}", row * col);
}
println!(); // end the row
} 1 2 3 4
2 4 6 8
3 6 9 12Adapters and consumers
let squares: Vec<i32> = (1..=5).map(|x| x * x).collect(); // [1, 4, 9, 16, 25]
let evens: Vec<&i32> = values.iter().filter(|&&x| x % 2 == 0).collect();
let total: i32 = values.iter().sum();
let count = values.iter().filter(|&&x| x > 50).count();
let any_big = values.iter().any(|&x| x > 50);
let all_pos = values.iter().all(|&x| x > 0);
let first_big = values.iter().find(|&&x| x > 50); // Option<&i32>
let names_upper: Vec<String> = names.iter().map(|n| n.to_uppercase()).collect();breakleaves the innermost loop;continueskips to the next turn. Labels reach outer loops:'outer: for ... { for ... { break 'outer; } }.for v in values(no&) moves the Vec into the loop and you cannot use it afterwards. Almost always writefor v in &values.|x| x * xis a closure: an anonymous function. The&&xpatterns infilterpeel off the reference layersiter()adds;iter().copied()avoids them for numbers.- Changing a Vec while iterating over it is a compile error (a borrow conflict), which is the bug it prevents.
Off-by-one still exists: 0..n versus 0..=n. Trace n = 1 by hand. Integer counters never drift the way float counters do; if you need a float sequence, count with an integer and compute the float inside.
Functions, Ownership and Borrowing
Control Flow · Rust 1
Declaring and Calling
A function packages a computation under a name. Parameter types are required; the return type follows ->. The last expression in the body, without a semicolon, is the return value. Functions may be defined before or after their callers.
/// Computes the volume of a cube with the given side length.
fn cube_volume(side_length: f64) -> f64 {
side_length * side_length * side_length // no semicolon: this is the value
}
/// Prints a boxed string. Returns nothing: the return type () is implied.
fn box_string(contents: &str) {
let line = "-".repeat(contents.len() + 2);
println!("{line}\n!{contents}!\n{line}");
}
fn main() {
let result = cube_volume(2.0); // the call; 2.0 is the argument
println!("{result}"); // 8
box_string("Hello");
}| Part | In the example | Rules |
|---|---|---|
| Header | fn cube_volume(side_length: f64) -> f64 | fn, the name, typed parameters, the return type |
| Body | between the braces | Statements end with ;; the final expression without one is returned |
return | return x; | Only needed to leave early; most functions end with a bare expression |
| Several results | -> (f64, f64) | Return a tuple and destructure it: let (w, h) = read_rect(); |
| Maybe no result | -> Option<f64> | Return Some(v) or None instead of a sentinel like -1 |
Ownership: The Rule That Makes Rust Rust
Every value has one owner, the variable that holds it. When the owner goes out of scope the value is freed. Assigning or passing a heap value such as a String or Vec moves it: the old variable is no longer usable. Simple values such as numbers, bools and chars are Copy: they are duplicated instead, and nothing moves.
Moves
let s1 = String::from("hello");
let s2 = s1; // MOVE: s1 is now invalid
println!("{s1}"); // error: borrow of moved value
let s3 = s2.clone(); // an explicit deep copy; both usable
let n1 = 5;
let n2 = n1; // Copy: numbers are duplicated
println!("{n1} {n2}"); // fine
fn takes(s: String) { println!("{s}"); } // s is dropped at the end of takes
let name = String::from("Ann");
takes(name); // name moved INTO the function
println!("{name}"); // error: value used after moveBorrowing: lend it, keep it
fn len_of(s: &String) -> usize { // &: a shared borrow; the caller keeps ownership
s.len()
}
let name = String::from("Ann");
let n = len_of(&name); // lend it
println!("{name} has {n} letters"); // still ours
fn shout(s: &mut String) { // &mut: a mutable borrow
s.push_str("!");
}
let mut greeting = String::from("Hi");
shout(&mut greeting); // the caller must say &mut too
println!("{greeting}"); // Hi!| The borrowing rules | Means | Why |
|---|---|---|
Any number of &T shared borrows at once | Many readers | Reading never conflicts |
or exactly one &mut T | One writer, no readers | No one sees a half-changed value; no iterator invalidation; no data races |
| A borrow cannot outlive what it borrows | No dangling references | The compiler tracks lifetimes so a reference to freed memory cannot exist |
“cannot borrow as mutable because it is also borrowed as immutable” is the borrow checker catching you holding a reference into a collection while changing it. The fix is almost always to end the first borrow (use it, or copy the value out) before the change.
How to debug a borrow-checker error, step by step
- 1. Read the first line and the code.
E0382is a use after a move;E0502andE0499are two borrows that overlap;E0596andE0384are a missingmut.rustc --explain E0502gives a page with examples. - 2. Find the two underlined places. The message labels them:
value moved hereandvalue borrowed here after move, orfirst borrow occurs hereandsecond borrow occurs here. The conflict is between those two lines, not where the arrow points alone. - 3. Ask whether you need the old value after the first place. If not, the move is fine: stop using the old name, or shadow it with a new
let. - 4. If you do need it, pick the cheapest repair: pass
&nameinstead ofnameand make the function take&stror&[T]; copy a number out (let first = v[0];) before thepush; reorder so the read finishes before the write; or.clone()when you genuinely need two copies. - 5. Follow the
help:line. It usually contains the exact edit, such as consider changing this parameter type in function `takes` to borrow instead if owning the value isn’t necessary. - 6. Recompile and re-read. Fixing one borrow often reveals the next; that is normal. A fix you do not understand, such as a
.clone()on every line, is a sign to go back to step 3.
| Code and first line | The situation | Fix |
|---|---|---|
E0382: borrow of moved value: `name` | takes(name); println!("{name}"); | takes(&name) and fn takes(s: &str), or takes(name.clone()) |
E0382: borrow of moved value: `values` | for v in values { ... } then values.len() | for v in &values |
E0502: cannot borrow `v` as mutable because it is also borrowed as immutable | let first = &v[0]; v.push(4); println!("{first}"); | let first = v[0]; (copy the number) or print before pushing |
E0499: cannot borrow `s` as mutable more than once at a time | Two live &mut s | Finish with the first before taking the second |
E0596: cannot borrow `v` as mutable, as it is not declared as mutable | let v = Vec::new(); v.push(1);, or calling an &mut self method | let mut v |
E0507: cannot move out of `r.name` which is behind a shared reference | let n = r.name; where r is a &Student | let n = &r.name; or r.name.clone() |
Parameters the Rust Way
Prefer slices to owned types
fn average(values: &[f64]) -> f64 { // &[f64]: a slice; accepts a Vec, an array or part of either
if values.is_empty() { return 0.0; }
values.iter().sum::<f64>() / values.len() as f64
}
fn first_word(text: &str) -> &str { // &str, not &String: accepts both
text.split_whitespace().next().unwrap_or("")
}
let v = vec![1.0, 2.0, 3.0];
average(&v); // &Vec<f64> becomes &[f64] automatically
average(&v[1..]); // part of it
first_word("hello world");
first_word(&String::from("hello world"));Returning owned values is cheap
fn make_greeting(name: &str) -> String { // build and hand back; the caller now owns it
format!("Hello, {name}!")
}
fn add_interest(balance: f64, rate: f64) -> f64 { // numbers: take and return by value
balance + balance * rate / 100.0
}
fn append_bonus(scores: &mut Vec<i32>) { // change the caller's Vec through a mutable borrow
scores.push(10);
}
let mut my_scores = vec![90, 85];
append_bonus(&mut my_scores);
println!("{my_scores:?}"); // [90, 85, 10]- Take
&str,&[T]and&Tfor things you only read;&mut Tfor things you change;T(by value) when the function needs to keep or consume it. - Returning a
StringorVecmoves it out to the caller: no copy, no cost. - Scope: a variable lives from its
letto the end of its block. Shadowing with a newletis idiomatic for conversions:let line = line.trim();. - Closures
|x| x + 1capture variables from the surrounding scope by borrow, or by move withmove |x| .... - Stepwise refinement works as everywhere: write
mainas calls to functions that do not exist yet, then write them. Put each in its own module when the file grows.
Lists: Arrays, Vec and Slices
Data · Rust 1
Arrays and Vec
An array [T; N] has a fixed length known at compile time and lives on the stack. A Vec<T> grows and shrinks and lives on the heap; it is what you reach for by default. Both hold one type, index from 0 with a usize, and panic if you index past the end, never silently misbehave.
let primes = [2, 3, 5, 7, 11]; // array: [i32; 5]
let zeros = [0.0; 10]; // ten zeros: [f64; 10]
let mut values: Vec<f64> = Vec::new(); // empty Vec; the type is needed until you push
values.push(32.0); // append (values must be mut)
values.push(54.0);
let mut scores = vec![88, 92, 79]; // the vec! macro: a Vec with contents
let first = scores[0]; // 88
let last = scores[scores.len() - 1]; // 79 (or *scores.last().unwrap())
scores[1] = 95; // replace
let n = scores.len(); // 3
scores[5]; // PANIC: index out of bounds
let safe = scores.get(5); // None: the non-panicking way
let popped = scores.pop(); // Some(79); the Vec shrinksVisiting every element
for v in &values { // borrow: values stays usable
println!("{v}");
}
for v in &mut values { // change in place
*v *= 2.0;
}
for (i, v) in values.iter().enumerate() { // index and value
println!("{i}: {v}");
}
for i in 0..values.len() { // only when you must compute indexes
println!("{}", values[i]);
}Common algorithms
let total: f64 = values.iter().sum();
let largest = values.iter().cloned().fold(f64::MIN, f64::max);
let largest_int = *scores.iter().max().unwrap(); // Option<&i32>: unwrap and deref
let average = total / values.len() as f64;
let position = scores.iter().position(|&s| s == 95); // Option<usize>
let found = scores.contains(&95);
scores.swap(0, 2); // swap two elementsVec Methods and Slices
| Operation | Does | Returns |
|---|---|---|
v.push(x) / v.pop() | Add to / remove from the end | () / Option<T> |
v.insert(i, x) / v.remove(i) | Insert at i (later ones shift) / remove at i | () / the element; both panic if i is out of range |
v.len(), v.is_empty() | Count; emptiness test | usize, bool |
v.get(i) | Element at i without panicking | Option<&T> |
v.contains(&x) | Membership (needs &) | bool |
v.sort(), v.sort_by(...), v.reverse() | In place | () |
v.iter().rev(), v.dedup(), v.retain(|x| ...) | Reversed iterator; drop adjacent duplicates; keep matching elements | |
v.extend(other), v.clear(), v.truncate(n) | Append all; empty; cut to n | |
v.join(", ") | Vec of strings into one String | String |
Slices: a view into part of a sequence
let v = vec![10, 20, 30, 40, 50];
let middle = &v[1..3]; // &[i32]: [20, 30], borrowed, not copied
let head = &v[..2]; // [10, 20]
let tail = &v[3..]; // [40, 50]
let whole: &[i32] = &v; // the whole Vec as a slice
fn total(xs: &[i32]) -> i32 { xs.iter().sum() }
total(&v); // works on a Vec...
total(&primes); // ...an array...
total(&v[1..3]); // ...or part of eitherMoves, clones and the no-aliasing rule
let a = vec![1, 2, 3];
let b = a; // MOVE: a is gone; there is no aliasing bug to have
let c = b.clone(); // a real copy, on purpose
println!("{b:?} {c:?}");
let mut v = vec![1, 2, 3];
let first = &v[0]; // a shared borrow into v...
v.push(4); // ...error: cannot borrow v as mutable
println!("{first}"); // (because first might now point at freed memory)
// fix: let first = v[0]; (copy the number) before pushingIndexing panics on a bad index; get does not. v[i] is right when the index is known to be valid (a loop over 0..v.len()). When it comes from input or a search, use v.get(i) and match.
Transforming, Tuples and Tables
Build new Vecs with iterators
let squares: Vec<i32> = (1..=5).map(|x| x * x).collect();
let evens: Vec<i32> = values.iter().copied().filter(|x| x % 2 == 0).collect();
let names_upper: Vec<String> = names.iter().map(|n| n.to_uppercase()).collect();
let total: i32 = values.iter().sum();
let (small, big): (Vec<i32>, Vec<i32>) = values.iter().partition(|&&x| x < 50);
let words: Vec<&str> = line.split_whitespace().collect();
let mut sorted = values.clone();
sorted.sort();Tuples
let point = (3, 4); // (i32, i32)
let (x, y) = point; // destructure
let x2 = point.0; // or by position
let rgb: (u8, u8, u8) = (255, 128, 0);
fn min_max(xs: &[i32]) -> (i32, i32) {
(*xs.iter().min().unwrap(), *xs.iter().max().unwrap())
}
let (lo, hi) = min_max(&v);Two-dimensional data
// A table: a Vec of rows, each row a Vec
let mut table = vec![vec![0; 4]; 3]; // 3 rows of 4 zeros; vec! clones the row, so they are independent
table[1][2] = 7;
for row in &table {
let line: Vec<String> = row.iter().map(|v| format!("{v:4}")).collect();
println!("{}", line.join(""));
}
let rows = table.len();
let cols = table[0].len();
let column_total: i32 = table.iter().map(|row| row[1]).sum();
// a fixed-size grid on the stack:
let mut board = [[0u8; 8]; 8];
board[3][4] = 1; 0 0 0 0
0 0 7 0
0 0 0 0Mistakes to watch for
- Indexing with the wrong integer type:
v[i]withi: i32isE0277: the type `[i32]` cannot be indexed by `i32`. Indexes areusize; writei as usizeor keep the counter ausizefrom the start. collect()with nothing telling it what to build:E0283: type annotations needed. Put the type on thelet(let evens: Vec<i32> = ...) or use the turbofishcollect::<Vec<i32>>().- Comparing through the references
iter()hands out:.filter(|x| x > 1)isE0308: mismatched types ... expected `&&i32`, found integer. Peel them with the pattern|&&x| x > 1, or call.copied()first as theevensline above does. - A bad index is not a compile error but a panic at run time:
index out of bounds: the len is 3 but the index is 5. The line number in the panic message is thev[i]that failed.
Files and Error Handling with Result
Data · Rust 1
Reading and Writing Text Files
src/main.rs
use std::fs;
fn main() {
// Copy input.txt to output.txt with line numbers
let text = fs::read_to_string("input.txt").expect("could not read input.txt");
let numbered: Vec<String> = text
.lines()
.enumerate()
.map(|(i, line)| format!("/* {} */ {}", i + 1, line))
.collect();
fs::write("output.txt", numbered.join("\n")).expect("could not write output.txt");
}$ cargo run # with input.txt missing
thread 'main' panicked at src/main.rs:5:55:
could not read input.txt: Os { code: 2, kind: NotFound, message: "No such file or directory" }That is what expect does: your message, a colon, then the error value. With unwrap() the first part would read called `Result::unwrap()` on an `Err` value: instead, which is why expect with the file name is the better habit while learning.
| Call | Does |
|---|---|
fs::read_to_string(path) | The whole file as a String; Err if it does not exist or is not UTF-8 |
fs::write(path, text) | Writes a string or bytes; creates the file or erases an existing one |
text.lines() | An iterator over the lines, newlines removed |
File::open(path) + BufReader::new(file).lines() | Line by line without loading everything, for big files; each line is a Result<String> |
File::create(path) + writeln!(file, ...) | Write piece by piece; use std::io::Write |
OpenOptions::new().append(true).open(path) | Append to the end |
Path::new(p).exists() | Test before opening |
How to read a file safely, step by step
- 1. Pick the reading call.
fs::read_to_stringfor anything that fits in memory (almost everything in a first course);BufReader::new(File::open(path)?).lines()for a file too big to hold at once. - 2. Decide who handles failure. In
mainwhile learning,.expect("could not read input.txt")with the file name in the message. In any other function, returnResult<_, Box<dyn Error>>and put?after the call, so the caller decides. - 3. Split into lines with
.lines(). It already removes the\n; still call.trim()on each line beforeparse(), because a stray space or a Windows\rmakesparsefail. - 4. Convert with
parse()and look at theResult:matchorif let Ok(v)when a bad line should be reported,filter_map(|l| l.trim().parse().ok())when bad lines should be skipped on purpose. - 5. Nothing to close. A
Filecloses when it goes out of scope, on every path.
Mistakes to watch for
- Running from the wrong folder.
cargo runruns in the project folder (whereCargo.tomlis), not insrc/. A file next tomain.rsgivesNotFound; move it up one level or write"src/input.txt". - Using the lines from
BufReaderdirectly:line.split(", ")without thelet line = line?;step isE0599: the method `split` exists for enum `Result<String, std::io::Error>`, but its trait bounds were not satisfied. Each line is aResultuntil you unwrap it. ?inside a function that returns nothing:E0277: the `?` operator can only be used in a function that returns `Result` or `Option`. Changemaintofn main() -> Result<(), Box<dyn Error>>and end it withOk(()), as shown below.
Line by line, and taking a line apart
use std::fs::File;
use std::io::{BufRead, BufReader};
let file = File::open("data.txt")?; // ? explained below
for line in BufReader::new(file).lines() {
let line = line?; // each line is a Result<String>
let parts: Vec<&str> = line.split(", ").collect(); // "Smith, Jane, 92"
let score: i32 = parts[2].parse()?;
println!("{} {}: {}", parts[1], parts[0], score);
}Reading numbers
// One per line, skipping blanks and bad lines
let values: Vec<f64> = fs::read_to_string("numbers.txt")?
.lines()
.filter_map(|l| l.trim().parse().ok())
.collect();
// Several per line
let mut total = 0.0;
for token in text.split_whitespace() {
total += token.parse::<f64>()?;
}Paths are relative to the working directory, usually the project folder when you use cargo run. Command-line arguments: let args: Vec<String> = std::env::args().collect();, and args[1] is the first one.
Errors Are Values: Result and Option
Rust has no exceptions. A function that can fail returns Result<T, E>: Ok(value) or Err(error). A value that might be absent is an Option<T>: Some(value) or None. The compiler makes you look inside before you can use the value, so forgetting to handle an error is a compile error, not a surprise at 3 a.m.
Taking a Result apart
match "42".parse::<i32>() {
Ok(n) => println!("Got {n}"),
Err(e) => println!("Not a number: {e}"),
}
match fs::read_to_string("input.txt") {
Ok(text) => process(&text),
Err(e) => eprintln!("Could not read input.txt: {e}"),
}
if let Ok(n) = line.trim().parse::<i32>() { // when only success matters
total += n;
}The shortcuts
| Call | Does | Use when |
|---|---|---|
.unwrap() | The value, or panic | Examples, tests, “cannot fail here” |
.expect("message") | The value, or panic with your message | Same, with a reason in the crash log |
.unwrap_or(default) | The value, or a default | A missing value has a sensible stand-in |
.unwrap_or_else(|e| ...) | The value, or compute one from the error | |
.ok() | Result → Option (drops the error) | With filter_map |
.map(|v| ...) | Transform the inside if Ok/Some | Chaining |
? | Unwrap, or return the error to the caller | Inside a function that itself returns Result |
The ? Operator and Your Own Errors
Propagating with ?
use std::error::Error;
use std::fs;
fn total_of_file(path: &str) -> Result<f64, Box<dyn Error>> {
let text = fs::read_to_string(path)?; // on Err: return it immediately
let mut total = 0.0;
for token in text.split_whitespace() {
total += token.parse::<f64>()?; // a different error type: Box<dyn Error> accepts any
}
Ok(total) // wrap the success value
}
fn main() -> Result<(), Box<dyn Error>> { // main may return Result too
let total = total_of_file("numbers.txt")?;
println!("{total}");
Ok(())
}A custom error type
use std::fmt;
#[derive(Debug)]
enum BankError {
InsufficientFunds { balance: f64, requested: f64 },
AccountFrozen,
}
impl fmt::Display for BankError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
BankError::InsufficientFunds { balance, requested } =>
write!(f, "cannot withdraw {requested}: balance is {balance}"),
BankError::AccountFrozen => write!(f, "account is frozen"),
}
}
}
impl std::error::Error for BankError {}
fn withdraw(balance: f64, amount: f64) -> Result<f64, BankError> {
if amount > balance {
return Err(BankError::InsufficientFunds { balance, requested: amount });
}
Ok(balance - amount)
}- Return
Resultfrom anything that can fail; let the caller decide.?keeps that from being verbose. - Handle at the edge:
mainor the input loop prints the message; inner functions just pass errors up. - Panics (
unwrap, bad indexes, overflow in debug) are for bugs, not for expected failures such as a missing file or bad input. - There is no
finallybecause there is no need: aFilecloses itself when it goes out of scope (RAII), on every path including errors. #[derive(Debug)]on your error type lets{:?}andunwrapprint it.
“the ? operator can only be used in a function that returns Result or Option” means you used ? inside a plain function. Either change its return type to Result<..., Box<dyn Error>> or handle the error with match right there.
Sets and Dictionaries: HashSet and HashMap
Data · Rust 1
HashSet
A HashSet holds values with no duplicates and no particular order. Inserting a value that is already there does nothing and returns false. Use a set when the question is only “is it in there?” BTreeSet is the sorted version.
use std::collections::HashSet;
let mut names: HashSet<String> = HashSet::new();
names.insert("Romeo".to_string());
names.insert("Juliet".to_string());
let was_new = names.insert("Romeo".to_string()); // false: already present
println!("{}", names.len()); // 2
println!("{}", names.contains("Juliet")); // true: very fast; &str works for a HashSet<String>
names.remove("Romeo");
let mut sorted: Vec<&String> = names.iter().collect(); // sets have no order
sorted.sort(); // sort for display
let distinct: HashSet<&str> = words.iter().copied().collect(); // the distinct words in a Vec| Operation | Call | Note |
|---|---|---|
| Union: in either | a.union(&b) | Iterators over references; .cloned().collect() for a new set |
| Intersection: in both | a.intersection(&b) | |
| Difference: in a but not b | a.difference(&b) | |
| Subset test | a.is_subset(&b) | bool |
Elements must implement Hash and Eq: integers, strings, chars, bools and tuples of them do. f64 does not (because of NaN), and your own structs do with #[derive(Hash, PartialEq, Eq)].
HashMap
A HashMap stores key → value pairs. Each key appears once and looks up its value directly. get returns an Option, so a missing key is handled at compile time, not with a crash. BTreeMap keeps the keys sorted.
use std::collections::HashMap;
let mut scores: HashMap<String, i32> = HashMap::new();
scores.insert("Harry".to_string(), 90); // add or replace (returns the old value as Option)
scores.insert("Sally".to_string(), 95);
let s = scores.get("Harry"); // Some(&90): an Option<&i32>
let fred = scores.get("Fred").copied().unwrap_or(0); // 0 instead of None
let has = scores.contains_key("Sally");
scores.remove("Harry");
println!("{}", scores.len());
for (name, score) in &scores { // key and value together, in no particular order
println!("{name} -> {score}");
}
for name in scores.keys() { /* ... */ }
let total: i32 = scores.values().sum();
if let Some(score) = scores.get_mut("Sally") { // change a value in place
*score += 5;
}Counting with the entry API
// How many times does each word occur?
let mut counts: HashMap<&str, usize> = HashMap::new();
for word in text.split_whitespace() {
*counts.entry(word).or_insert(0) += 1; // insert 0 if absent, then add 1
}
// the most common word
let best = counts.iter().max_by_key(|(_, &c)| c); // Option<(&&str, &usize)>
if let Some((word, c)) = best {
println!("{word}: {c}");
}// with text = "the cat and the hat and the bat"
the: 3
// println!("{counts:?}") prints the five pairs in a DIFFERENT order every run:
// {"and": 2, "the": 3, "bat": 1, "cat": 1, "hat": 1}entry(word).or_insert(0) returns a &mut usize pointing into the map, which is why the * is needed to add to it. A HashMap has no order at all, so for a report collect the pairs into a Vec and sort it, or use a BTreeMap. The key type is &str because the words borrow from text; the map must not outlive the String it points into.
Grouping with a map of Vecs
let mut by_letter: HashMap<char, Vec<&str>> = HashMap::new();
for name in &names {
let key = name.chars().next().unwrap();
by_letter.entry(key).or_default().push(name); // or_default: an empty Vec on first use
}
// sorted output: collect the keys and sort, or use a BTreeMap from the start
let mut keys: Vec<&char> = by_letter.keys().collect();
keys.sort();Building maps
let squares: HashMap<i32, i32> = (1..=5).map(|x| (x, x * x)).collect(); // from an iterator of pairs
let inverted: HashMap<i32, &String> = scores.iter().map(|(k, v)| (*v, k)).collect();
let lookup = HashMap::from([("one", 1), ("two", 2)]); // from an array of pairsThere is no map[key] that inserts. scores["Fred"] panics if the key is missing; scores.get("Fred") gives None; scores.entry("Fred") is how you insert-if-absent. Pick the one that says what you mean.
Choosing a Collection
| You need | Use |
|---|---|
| Values in order, by position, possibly repeated | Vec<T> |
| A fixed count known at compile time | an array [T; N] |
| A fixed group of related values of different types | a tuple, or better, a struct |
| Membership only, no duplicates | HashSet (or BTreeSet for sorted iteration) |
| Look up a value by a key | HashMap (or BTreeMap for sorted keys) |
| First in, first out | VecDeque (push_back, pop_front) |
| Last in, first out | Vec with push and pop |
| Always the smallest (or largest) first | BinaryHeap |
All of these live in std::collections; Vec and the string types are always available. Every one gives you len(), is_empty(), iter() and collect(), so the iterator adapters from Loops work on all of them.
Structs, impl Blocks and Enums
Objects and Algorithms · Rust 1
Structs Hold Data, impl Blocks Add Behavior
Rust has no class keyword. A struct declares the fields; an impl block attaches functions to it. Functions that take self are methods, called with a dot; functions without self are associated functions such as constructors, called with ::. Fields are private to the module unless marked pub.
bank_account.rs
/// A bank account has a balance that can be changed by deposits and withdrawals.
#[derive(Debug)] // lets {:?} print it
pub struct BankAccount {
balance: f64, // private outside this module
}
impl BankAccount {
/// Constructs an account with a zero balance. (A constructor is just a function named new.)
pub fn new() -> Self {
Self { balance: 0.0 }
}
/// Constructs an account with the given balance.
pub fn with_balance(initial_balance: f64) -> Self {
Self { balance: initial_balance }
}
/// Deposits money. &mut self: this method changes the account.
pub fn deposit(&mut self, amount: f64) {
self.balance += amount;
}
pub fn withdraw(&mut self, amount: f64) -> Result<(), String> {
if amount > self.balance {
return Err(format!("cannot withdraw {amount}: balance is {}", self.balance));
}
self.balance -= amount;
Ok(())
}
/// Gets the balance. &self: reads only.
pub fn balance(&self) -> f64 {
self.balance
}
}Using it
let mut harrys_checking = BankAccount::new(); // associated function, with ::
let mut moms_savings = BankAccount::with_balance(5000.0);
harrys_checking.deposit(2000.0); // method, with .
moms_savings.withdraw(500.0).unwrap();
println!("{}", harrys_checking.balance()); // 2000
println!("{moms_savings:?}"); // BankAccount { balance: 4500.0 }
harrys_checking.balance = 0.0; // error from another module: field is private2000
BankAccount { balance: 4500.0 }
error[E0616]: field `balance` of struct `BankAccount` is private // the last line, from another module
error[E0596]: cannot borrow `acct` as mutable, as it is not declared as mutable // if you forget let mut{} prints 2000, not 2000.0, because Display drops a trailing .0; {:?} keeps it. The two errors are the ones every first struct produces: reaching into a private field from outside the module (use the balance() method), and calling deposit on an account declared without mut.
The Three Kinds of self
| Receiver | Means | Use for |
|---|---|---|
&self | Borrow the object to read it | Accessors and anything that does not change the struct |
&mut self | Borrow it mutably | Mutators: the variable holding the object must be mut |
self | Take ownership; the object is consumed | Conversions and builders that give back a new value: fn into_summary(self) -> Summary |
| (none) | Not a method | Constructors (new), factories, helpers called as Type::name() |
Deriving the common behavior
#[derive(Debug, Clone, PartialEq)] // the compiler writes these for you
struct Point {
x: f64,
y: f64,
}
// Debug: println!("{p:?}") -> Point { x: 3.0, y: 4.0 }
// Clone: let q = p.clone();
// PartialEq: p == q compares every field
// also common: Copy (for small plain structs), Default, Hash, Eq, PartialOrd, Ord
impl Point {
fn distance_to(&self, other: &Point) -> f64 {
((self.x - other.x).powi(2) + (self.y - other.y).powi(2)).sqrt()
}
}Display: how it prints with {}
use std::fmt;
impl fmt::Display for BankAccount {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "BankAccount(balance={:.2})", self.balance)
}
}
// println!("{moms_savings}") -> BankAccount(balance=4500.00)
// also gives you .to_string() for freeStruct literals and update syntax
let p = Point { x: 3.0, y: 4.0 };
let x = 1.0;
let q = Point { x, y: 2.0 }; // field init shorthand when the variable has the field's name
let r = Point { y: 9.0, ..p }; // the rest copied from p
let Point { x: px, y: py } = p; // destructure
struct Pair(i32, i32); // a tuple struct: fields by position
let pair = Pair(1, 2);
println!("{}", pair.0);Ownership inside structs
struct Student {
name: String, // the struct OWNS its String
scores: Vec<i32>,
}
// A struct holding a &str or &T needs a lifetime, which is a later topic;
// while learning, store owned String and Vec and clone when you must.
let s = Student { name: "Ann".to_string(), scores: vec![90, 85] };
let n = s.name; // moves the String out: s.name is now unusable
let n2 = s.name.clone(); // copy instead when you need both“cannot borrow acct as mutable, as it is not declared as mutable”: calling an &mut self method on a variable declared with plain let. Add mut to the let. The compiler is making you say, at the declaration, that this object will change.
Enums: Types With a Fixed Set of Shapes
A Rust enum is far more than a list of names: each variant can carry its own data. Together with match it models “one of these things” exactly, and Option and Result are just enums from the standard library.
An enum with data
#[derive(Debug)]
enum Shape {
Circle { radius: f64 },
Rectangle { width: f64, height: f64 },
Triangle(f64, f64, f64), // tuple-style variant
}
impl Shape {
fn area(&self) -> f64 {
match self { // every variant must be handled
Shape::Circle { radius } => std::f64::consts::PI * radius * radius,
Shape::Rectangle { width, height } => width * height,
Shape::Triangle(a, b, c) => {
let s = (a + b + c) / 2.0;
(s * (s - a) * (s - b) * (s - c)).sqrt()
}
}
}
}
let shapes = vec![Shape::Circle { radius: 2.0 }, Shape::Rectangle { width: 3.0, height: 4.0 }];
for s in &shapes {
println!("{s:?} has area {:.2}", s.area());
}Circle { radius: 2.0 } has area 12.57
Rectangle { width: 3.0, height: 4.0 } has area 12.00Inside match self the names in the pattern (radius, width, a, b, c) are references to the fields of that one variant, usable only in that arm. Delete the Triangle arm and the compiler answers E0004: non-exhaustive patterns: `&Shape::Triangle(_, _, _)` not covered.
Option and Result are enums
enum Option<T> { // in the standard library
Some(T),
None,
}
enum Result<T, E> {
Ok(T),
Err(E),
}
// so everything you learned about match applies:
fn describe(x: Option<i32>) -> String {
match x {
Some(n) if n < 0 => "negative".to_string(),
Some(0) => "zero".to_string(),
Some(n) => format!("positive {n}"),
None => "nothing".to_string(),
}
}- Use a struct when every value has all the fields (a point, an account).
- Use an enum when a value is one of several kinds, each with its own data (a shape, a message, a command).
- Use
Option<T>for a field that may be absent instead of a sentinel like -1 or an empty string. - Design starts with the public interface: which methods, taking
&selfor&mut self? Then pick the fields, keep them private, and letnewenforce the invariants.
Traits and Generics (Rust Has No Inheritance)
Objects and Algorithms · Rust 1
Why There Is No extends
Rust deliberately has no class inheritance. Where Java or Python would make SavingsAccount extends BankAccount, Rust uses two tools: composition (a struct contains another struct) to share data and behavior, and traits (shared interfaces, like Java interfaces with default methods) to let different types be treated the same way. Everything a hierarchy gives you, these give you without the fragile-base-class problems.
Composition: has-a instead of is-a
pub struct SavingsAccount {
account: BankAccount, // contains one; the fields stay private to BankAccount
interest_rate: f64,
}
impl SavingsAccount {
pub fn new(rate: f64) -> Self {
Self { account: BankAccount::new(), interest_rate: rate }
}
pub fn add_interest(&mut self) {
let interest = self.account.balance() * self.interest_rate / 100.0;
self.account.deposit(interest);
}
// forward what callers need (or expose the inner account)
pub fn deposit(&mut self, amount: f64) { self.account.deposit(amount); }
pub fn balance(&self) -> f64 { self.account.balance() }
}A trait: the shared contract
pub trait Account {
fn deposit(&mut self, amount: f64);
fn balance(&self) -> f64;
fn describe(&self) -> String { // a DEFAULT method: types get it for free
format!("Account with balance {:.2}", self.balance())
}
}
impl Account for BankAccount {
fn deposit(&mut self, amount: f64) { self.balance += amount; }
fn balance(&self) -> f64 { self.balance }
}
impl Account for SavingsAccount {
fn deposit(&mut self, amount: f64) { self.account.deposit(amount); }
fn balance(&self) -> f64 { self.account.balance() }
fn describe(&self) -> String { // override the default
format!("Savings at {}%: {:.2}", self.interest_rate, self.balance())
}
}Polymorphism Two Ways
Generics: decided at compile time
// T can be ANY type that implements Account
fn print_all<T: Account>(accounts: &[T]) {
for a in accounts {
println!("{}", a.describe());
}
}
fn total_balance(accounts: &[impl Account]) -> f64 { // impl Trait: the short form
accounts.iter().map(|a| a.balance()).sum()
}
let savings = vec![SavingsAccount::new(2.5), SavingsAccount::new(3.0)];
print_all(&savings); // one type per call: all SavingsAccount hereTrait objects: decided at run time
// a Vec of DIFFERENT account types, through Box<dyn Account>
let mut accounts: Vec<Box<dyn Account>> = vec![
Box::new(BankAccount::with_balance(100.0)),
Box::new(SavingsAccount::new(2.5)),
];
for acct in accounts.iter_mut() {
acct.deposit(10.0); // the right deposit runs for each (dynamic dispatch)
println!("{}", acct.describe());
}
// dyn Account = "some type that implements Account, figured out at run time"
// Box puts it on the heap so every element has the same sizeAccount with balance 110.00
Savings at 2.5%: 10.00The first line comes from the trait’s default describe, because BankAccount did not write its own; the second from the override in impl Account for SavingsAccount. The Vec<Box<dyn Account>> type annotation is required: without it the compiler infers Vec<Box<BankAccount>> from the first element and rejects the second with E0308: mismatched types.
Generics <T: Trait> | Trait objects dyn Trait | |
|---|---|---|
| When the type is known | At compile time: one copy of the function per type (monomorphization) | At run time, through a vtable |
| Mixed types in one collection | No: Vec<T> is one T | Yes: Vec<Box<dyn Trait>> |
| Speed | As fast as hand-written code | One pointer hop per call, like Java |
| Use when | Most of the time | You genuinely need a heterogeneous collection or plugin-style behavior |
Traits You Will Use Every Day
| Trait | Gives you | How to get it |
|---|---|---|
Debug | {:?} printing | #[derive(Debug)] |
Display | {} printing and .to_string() | Write impl fmt::Display yourself |
Clone / Copy | .clone() / implicit copying for small plain types | #[derive(Clone, Copy)] |
PartialEq / Eq | == | #[derive(PartialEq, Eq)] |
PartialOrd / Ord | <, sort(), max() | #[derive(PartialOrd, Ord)], or implement cmp |
Hash | Use as a HashMap key or HashSet element | #[derive(Hash)] (with Eq) |
Default | Type::default() | #[derive(Default)] |
Iterator | for loops and every adapter | Implement next() |
From / Into | Conversions: let s: String = "x".into(); | Implement From<Other> for Mine |
Implementing a standard trait
use std::cmp::Ordering;
#[derive(Debug, PartialEq)]
struct Country {
name: String,
area: f64,
}
impl PartialOrd for Country {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.area.partial_cmp(&other.area) // compare by area
}
}
// now c1 < c2 works, and sort_by(|a, b| a.partial_cmp(b).unwrap())Rules of thumb
- Share behavior with a trait; share data by putting one struct inside another.
- Prefer
#[derive]to hand-written impls whenever the obvious behavior is what you want. - Take
impl Traitor&dyn Traitin function parameters so callers can pass any suitable type. - A trait can require other traits (
trait Account: Display) and can be implemented for types you did not write, including standard ones, as long as you own the trait. - Type checking is structural by contract: a type is an
Accountif and only if there is animpl Account forit. No accidental matches, no casting.
Recursion
Objects and Algorithms · Rust 1
A Function That Calls Itself
A recursive function solves a problem by solving a smaller version of the same problem, then doing one more step. Every recursion needs two things: a base case answered directly, and a recursive case that moves toward the base case. Rust requires the return type on recursive functions, which it always does anyway.
Factorial
fn factorial(n: u64) -> u64 {
if n <= 1 { // base case
1
} else {
n * factorial(n - 1) // recursive case: smaller n
}
}
// factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * 2 * 1 = 24
// factorial(21) overflows u64: in debug builds that is a panic
// ("attempt to multiply with overflow"), not a silently wrong answerSum of digits
fn digit_sum(n: u64) -> u64 {
if n < 10 {
n
} else {
digit_sum(n / 10) + n % 10
}
}
// digit_sum(1729) = digit_sum(172) + 9 = (digit_sum(17) + 2) + 9 = ((1 + 7) + 2) + 9 = 19Palindrome
fn is_palindrome(s: &str) -> bool {
let chars: Vec<char> = s.chars().collect(); // work on chars, not bytes
fn check(c: &[char]) -> bool { // a nested helper on a slice
c.len() <= 1 || (c[0] == c[c.len() - 1] && check(&c[1..c.len() - 1]))
}
check(&chars)
}How to write a recursive function, step by step
- 1. Write the signature first, with the return type:
fn factorial(n: u64) -> u64. Rust will not infer it, and deciding it settles what the base case must return. - 2. Write the base case as the first branch of an
iformatch:if n <= 1 { 1 },if c.len() <= 1 { true }, an empty slice. - 3. Shrink the input toward it:
n - 1,n / 10,&c[1..c.len() - 1]. With unsigned types check the base case before subtracting, or0 - 1panics withattempt to subtract with overflow. - 4. Call yourself on the smaller input and trust the result.
- 5. Combine it with the piece you kept:
n * ...,... + n % 10,c[0] == c[last] && .... Both branches must produce the same type, or you getE0308: `if` and `else` have incompatible types. - 6. Test the base case and one step above it (
factorial(1),factorial(2)); if those two pass, induction does the rest.
Thinking recursively
- Trust the recursive call. Assume
checkworks for shorter slices; your job is only the first and last character. - Make sure each call is strictly smaller and that the smallest case is handled before any recursive call.
- Slices make “the rest of the input” free:
&c[1..]borrows without copying. - Trace tiny inputs by hand: the empty string, one character, two characters.
When Recursion Is Slow
// Fibonacci the obvious way: correct, but fib(40) makes over 300 million calls
fn fib(n: u32) -> u64 {
if n <= 2 { 1 } else { fib(n - 1) + fib(n - 2) }
}
// The same numbers with a loop: n steps
fn fib_loop(n: u32) -> u64 {
let (mut older, mut old) = (1, 1);
for _ in 2..n {
(older, old) = (old, older + old);
}
old
}
// Or remember answers you already have (memoization) in a HashMap
use std::collections::HashMap;
fn fib_memo(n: u32, memo: &mut HashMap<u32, u64>) -> u64 {
if n <= 2 { return 1; }
if let Some(&v) = memo.get(&n) { return v; }
let v = fib_memo(n - 1, memo) + fib_memo(n - 2, memo);
memo.insert(n, v);
v
}- When the recursive case calls itself twice on overlapping problems, the work doubles at every level. Use a loop or memoization.
- Each call uses a stack frame; the main thread’s stack is about 8 MB. Deep recursion ends with
thread 'main' has overflowed its stack; a loop would not. - Recursion shines when the problem is naturally nested: permutations, subsets, folders inside folders, trees, and “try every choice” searches.
Permutations, Hanoi and Trees
All permutations of a string
fn permutations(word: &str) -> Vec<String> {
if word.is_empty() {
return vec![String::new()]; // one permutation of the empty string
}
let chars: Vec<char> = word.chars().collect();
let mut result = Vec::new();
for i in 0..chars.len() {
let mut shorter = chars.clone();
let ch = shorter.remove(i);
let rest: String = shorter.into_iter().collect();
for p in permutations(&rest) {
result.push(format!("{ch}{p}"));
}
}
result
}
// permutations("eat") -> ["eat", "eta", "aet", "ate", "tea", "tae"]Towers of Hanoi
/// Moves n disks from source to target using spare.
fn hanoi(n: u32, source: &str, target: &str, spare: &str) {
if n == 0 {
return;
}
hanoi(n - 1, source, spare, target);
println!("Move disk {n} from {source} to {target}");
hanoi(n - 1, spare, target, source);
}
// hanoi(3, "A", "C", "B") prints 7 moves; n disks take 2^n - 1Recursion over a tree
// A recursive data type needs a Box so its size is known: a tree node holds boxes of nodes
#[derive(Debug)]
struct Node {
value: i32,
children: Vec<Box<Node>>,
}
fn sum(node: &Node) -> i32 {
node.value + node.children.iter().map(|c| sum(c)).sum::<i32>()
}
fn depth(node: &Node) -> usize {
1 + node.children.iter().map(|c| depth(c)).max().unwrap_or(0)
}Mutual recursion is two functions that call each other, such as an expression evaluator where expression calls term, which calls factor, which calls expression again for a parenthesized part. Rust does not care about definition order, so no forward declarations are needed.
Sorting and Searching
Objects and Algorithms · Rust 1
Selection Sort and Insertion Sort
Selection sort
fn selection_sort(a: &mut [i32]) { // a slice: works on a Vec or an array
for i in 0..a.len().saturating_sub(1) {
let mut min_pos = i; // find the smallest in a[i..]
for j in i + 1..a.len() {
if a[j] < a[min_pos] {
min_pos = j;
}
}
a.swap(i, min_pos); // swap it into position i
}
}Insertion sort
fn insertion_sort(a: &mut [i32]) {
for i in 1..a.len() {
let next = a[i]; // a[0..i] is already sorted
let mut j = i;
while j > 0 && a[j - 1] > next { // slide bigger ones right
a[j] = a[j - 1];
j -= 1;
}
a[j] = next; // drop next into the gap
}
}// insertion_sort(&mut [5, 3, 8, 1]), printing a after each pass:
after i = 1: [3, 5, 8, 1] // 3 slid left past 5
after i = 2: [3, 5, 8, 1] // 8 already in place: the while loop ran zero times
after i = 3: [1, 3, 5, 8] // 1 slid left past 8, 5 and 3To see this yourself add println!("after i = {i}: {a:?}"); as the last line of the outer for. The check at every pass: a[..=i] is sorted, the rest untouched. Note let next = a[i]; copies the number out before the shifting starts; with a Vec<String> you would need a.swap or clone(), because moving out of an index is E0507.
Both make about n²/2 comparisons: doubling the data quadruples the time. Insertion sort is fast on data that is already nearly sorted; selection sort always does the same work. Note saturating_sub(1): a.len() - 1 on an empty slice would underflow a usize and panic.
Merge Sort
fn merge_sort(a: &[i32]) -> Vec<i32> {
if a.len() <= 1 {
return a.to_vec();
}
let mid = a.len() / 2;
let first = merge_sort(&a[..mid]); // sort each half
let second = merge_sort(&a[mid..]);
merge(&first, &second) // then merge them
}
fn merge(first: &[i32], second: &[i32]) -> Vec<i32> {
let mut merged = Vec::with_capacity(first.len() + second.len());
let (mut i, mut j) = (0, 0);
while i < first.len() && j < second.len() {
if first[i] < second[j] {
merged.push(first[i]);
i += 1;
} else {
merged.push(second[j]);
j += 1;
}
}
merged.extend_from_slice(&first[i..]); // whatever is left over
merged.extend_from_slice(&second[j..]);
merged
}
// returns a NEW sorted Vec: let sorted = merge_sort(&values);| Algorithm | Comparisons for n items | Big-O | Doubling n makes it |
|---|---|---|---|
| Selection sort | about n²/2 | O(n²) | 4 times slower |
| Insertion sort | n²/4 average; n if already sorted | O(n²) | 4 times slower |
| Merge sort | about n log2 n | O(n log n) | a little more than 2 times slower |
slice::sort (stable, driftsort) / sort_unstable (ipnsort) | n log n; faster on nearly sorted data | O(n log n) | a little more than 2 times slower |
| Linear search | n/2 average, n worst | O(n) | 2 times slower |
| Binary search (sorted data) | about log2 n | O(log n) | one more step |
Big-O keeps only the fastest-growing term and drops constants: 3n² + 20n + 7 is O(n²). It describes how the work scales, not how many seconds it takes.
Searching
Linear search
fn linear_search(a: &[i32], value: i32) -> Option<usize> {
for (i, &x) in a.iter().enumerate() {
if x == value {
return Some(i);
}
}
None
}
// built in: a.iter().position(|&x| x == value), a.contains(&value), a.iter().find(...)Binary search (the slice must be sorted)
fn binary_search(a: &[i32], value: i32) -> Option<usize> {
let (mut low, mut high) = (0usize, a.len()); // half-open: [low, high)
while low < high {
let mid = low + (high - low) / 2; // no overflow, no negative numbers
if a[mid] == value {
return Some(mid);
} else if a[mid] < value {
low = mid + 1;
} else {
high = mid;
}
}
None
}
// 1,000,000 sorted items: at most 20 steps
// built in: a.binary_search(&value) -> Ok(index) or Err(where it would go)
// binary_search(&[1, 3, 5, 7, 9, 11], 7) -> Some(3)
// binary_search(&[1, 3, 5, 7, 9, 11], 4) -> None
// [1, 3, 5, 7, 9, 11].binary_search(&4) -> Err(2): 4 would be inserted at index 2The library does it faster: use these in real programs
values.sort(); // in place, ascending, stable (integers, strings)
values.sort_unstable(); // faster when equal elements need not keep order
values.sort_by(|a, b| b.cmp(a)); // descending
floats.sort_by(|a, b| a.partial_cmp(b).unwrap()); // f64 has no total order (NaN): say what to do
floats.sort_by(|a, b| a.total_cmp(b)); // or use total_cmp
names.sort_by_key(|n| n.len()); // by another rule
names.sort_by_key(|n| n.to_lowercase()); // case-insensitive
people.sort_by_key(|p| p.age); // structs, by one field
people.sort_by(|a, b| a.last.cmp(&b.last).then(a.first.cmp(&b.first))); // by two
let sorted: Vec<i32> = { let mut v = values.clone(); v.sort(); v }; // a sorted copy
let pos = sorted.binary_search(&42); // Result<usize, usize>Sorting your own structs
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] // derive compares fields IN ORDER: area first, then name
struct Country {
area: u64,
name: String,
}
countries.sort(); // uses the derived Ord
// or decide the order yourself:
use std::cmp::Ordering;
impl Ord for Country {
fn cmp(&self, other: &Self) -> Ordering {
self.area.cmp(&other.area)
}
}
impl PartialOrd for Country {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
}Ord vs sort_by_key
Ordon the type gives one natural order thatsort(),max(),min(),BTreeMapandBinaryHeapall use.sort_by_keyandsort_bypick a different order for one call without touching the type.- Comparisons return an
Ordering:Less,EqualorGreater.a.cmp(&b)for integers and strings;partial_cmportotal_cmpfor floats. sortis stable: items that compare equal keep their original order, so you can sort by last name after sorting by first name.