Rust Fundamentals for Beginners: Ownership, Types and Cargo
Learn Rust from zero: Cargo, variables and types, control flow, ownership and borrowing, structs, enums and pattern matching, collections and error handling, with quizzes.
Study this lesson with its quizzes on Brainbotox →
What is Rust? Cargo and your first program
Rust is a compiled systems programming language that guarantees memory safety and thread safety at compile time, without a garbage collector. Its build tool and package manager is called Cargo.
Why Rust
- Fast: compiles to native code, with performance comparable to C and C++.
- Safe: the compiler rejects use-after-free, dangling pointers and data races.
- No garbage collector: memory is released deterministically through ownership.
Your first project
cargo new hello cd hello cargo run
// src/main.rs
fn main() {
println!("Hello, world!");
}println! ends with ! because it is a macro, not a function.
Cargo commands
| Command | What it does |
|---|---|
cargo new | Creates a project with Cargo.toml and src/main.rs |
cargo check | Type-checks quickly without producing a binary |
cargo build | Compiles in debug mode |
cargo build --release | Compiles with optimisations |
cargo run | Builds and runs |
cargo test | Runs the tests |
Cargo.toml.rustup. Format with cargo fmt and lint with cargo clippy. Read compiler errors carefully: they usually explain the fix.Check yourself
- How does Rust manage memory?
- What is Cargo?
- Why does println! end with an exclamation mark?
- Which command type-checks code quickly without building a binary?
- What is a crate?
- Which flag produces an optimised build?
Rust variables, mutability and data types
In Rust, variables are immutable by default: you must write mut to be allowed to change one. Every value has a type known at compile time, usually inferred.
let, mut and shadowing
let x = 5; // x = 6; // error: cannot assign twice to immutable variable let mut y = 5; y = 6; // fine let text = "42"; let text = text.len(); // shadowing: a new variable, may change type const MAX_USERS: u32 = 1000; // type annotation required
Scalar types
| Family | Types | Default |
|---|---|---|
| Signed integers | i8 i16 i32 i64 i128 isize | i32 |
| Unsigned integers | u8 u16 u32 u64 u128 usize | |
| Floats | f32 f64 | f64 |
| Boolean | bool | |
| Character | char: 4 bytes, one Unicode scalar value |
Compound types
let point: (i32, f64) = (3, 1.5); let (a, b) = point; // destructuring let first = point.0; let nums: [i32; 3] = [1, 2, 3]; // fixed-size array let zeros = [0; 5]; // five zeros
No implicit conversions
let i: i32 = 7; let f = i as f64 / 2.0; // 3.5: cast with as let n = i / 2; // 3: integer division
checked_add, wrapping_add or saturating_add to state what you want.Check yourself
- What is true of a variable declared with let x = 5; in Rust?
- What is shadowing?
- What is the default integer type in Rust?
- How do you convert an i32 to f64?
- What happens on integer overflow in a debug build?
- How large is a Rust char?
Rust control flow, functions and expressions
Rust is an expression-based language: if, match and blocks produce values, and a function returns the value of its last expression.
Functions
fn add(a: i32, b: i32) -> i32 {
a + b // no semicolon: this expression is the return value
}a + b;) turns the expression into a statement, and the function would return (), the unit type: a compile error here.Parameter types are always written. return exists for early exits.
if is an expression
let label = if score >= 50 { "pass" } else { "fail" };The condition must be a bool, and both branches must have the same type.
Loops
for i in 0..3 { println!("{i}"); } // 0 1 2 (end excluded)
for i in 0..=3 { } // 0 1 2 3 (end included)
for item in [10, 20, 30] { }
while n > 0 { n -= 1; }
let found = loop {
counter += 1;
if counter == 10 { break counter * 2; } // loop returns a value
};match
let kind = match n {
0 => "zero",
1 | 2 => "small",
3..=9 => "medium",
_ => "large", // catch-all
};match must be exhaustive: every possible value has to be covered, or the code does not compile.Check yourself
- What does fn add(a: i32, b: i32) -> i32 { a + b } return?
- Which values does for i in 0..3 produce?
- In Rust, if can be used on the right side of let to produce a value.
- What must a match expression be?
- Which loop can return a value through break?
- What is ()?
Rust ownership and borrowing explained
Ownership is Rust's central idea: every value has exactly one owner, and the value is freed automatically when that owner goes out of scope. Borrowing lets other code use a value without taking ownership.
The three ownership rules
- Each value has an owner.
- There is only one owner at a time.
- When the owner goes out of scope, the value is dropped.
Move
let s1 = String::from("hello");
let s2 = s1; // ownership moves to s2
// println!("{s1}"); // error: borrow of moved value
let s3 = s2.clone(); // explicit deep copy: both are validPassing a value to a function also moves it. Simple types that live entirely on the stack (i32, f64, bool, char) implement Copy: they are copied, not moved.
Borrowing with references
fn length(s: &String) -> usize { s.len() } // borrows, does not own
fn shout(s: &mut String) { s.push_str("!"); } // mutable borrow
let mut text = String::from("hi");
let n = length(&text);
shout(&mut text);The borrowing rules
&T) or exactly one mutable reference (&mut T), never both. And a reference must never outlive the value it points to.let mut v = vec![1, 2, 3];
let first = &v[0];
// v.push(4); // error: v is borrowed as immutable
println!("{first}");The part of the compiler that enforces this is the borrow checker. These rules are what prevent dangling pointers and data races.
Slices
let s = String::from("hello world");
let hello: &str = &s[0..5]; // a borrowed view of part of the stringCheck yourself
- After let s2 = s1; where s1 is a String, what is true?
- When is a value dropped?
- How many mutable references to a value can exist at once?
- Which type is copied, not moved, on assignment?
- What does passing &text to a function do?
- How do you make an explicit deep copy of a String?
Rust structs, enums and pattern matching
Structs group related data, enums define a type that is one of several variants, and match takes them apart safely. Rust has no null: absence is expressed with the enum Option.
Structs and methods
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn new(width: u32, height: u32) -> Self { // associated function
Self { width, height }
}
fn area(&self) -> u32 { self.width * self.height } // method
fn grow(&mut self, by: u32) { self.width += by; }
}
let mut r = Rectangle::new(3, 4);
r.grow(1);
println!("{}", r.area());| Receiver | Meaning |
|---|---|
&self | Reads the value |
&mut self | Modifies the value |
self | Takes ownership (consumes it) |
Enums with data
enum Shape {
Circle(f64),
Rect { w: f64, h: f64 },
}
fn area(s: &Shape) -> f64 {
match s {
Shape::Circle(r) => 3.14159 * r * r,
Shape::Rect { w, h } => w * h,
}
}Option: no null
fn find(id: u32) -> Option<String> {
if id == 1 { Some(String::from("Ada")) } else { None }
}
match find(2) {
Some(name) => println!("{name}"),
None => println!("not found"),
}
if let Some(name) = find(1) { println!("{name}"); }Option<T> is either Some(value) or None. You cannot use the inner value without handling the None case, which removes null pointer errors.#[derive(Debug)] above a struct or enum to print it with {:?}.Check yourself
- How does Rust represent a value that may be absent?
- Which method receiver allows modifying the struct?
- How is an associated function such as new called?
- Rust enum variants can carry data.
- What does if let Some(x) = value do?
- What does #[derive(Debug)] enable?
Rust collections, strings and error handling with Result
Rust's everyday collections are Vec, String and HashMap, and recoverable errors are returned as Result values, not thrown as exceptions.
Vec
let mut v = vec![1, 2, 3];
v.push(4);
let third = v[2]; // panics if out of bounds
let maybe = v.get(10); // None: safe access returns Option
for n in &v { println!("{n}"); }String and &str
| Type | What it is |
|---|---|
String | Owned, growable, heap-allocated UTF-8 text |
&str | A borrowed view of UTF-8 text (string literals are &str) |
let mut s = String::from("hello");
s.push_str(" world");
let view: &str = &s;
let msg = format!("{s}!");s[0]: characters take 1 to 4 bytes in UTF-8. Use s.chars() to iterate over characters.HashMap
use std::collections::HashMap;
let mut ages = HashMap::new();
ages.insert("Ada", 36);
if let Some(age) = ages.get("Ada") { println!("{age}"); }
*ages.entry("Bob").or_insert(0) += 1;Result and the ? operator
use std::fs;
use std::io;
fn read_number(path: &str) -> Result<i32, io::Error> {
let text = fs::read_to_string(path)?; // on Err: return it now
Ok(text.trim().parse().unwrap_or(0))
}
match read_number("n.txt") {
Ok(n) => println!("{n}"),
Err(e) => println!("failed: {e}"),
}Result<T, E> is Ok(value) or Err(error). The ? operator unwraps an Ok, or returns the Err from the current function immediately.unwrap, expect and panic
unwrap() and expect("message") return the inner value or panic. Use them in prototypes and tests, or where failure is truly impossible. panic! is for unrecoverable bugs.
Check yourself
- What does v.get(10) return on a Vec with three elements?
- What is the difference between String and &str?
- What does the ? operator do on an Err value?
- What does unwrap() do on None or Err?
- You can read the first character of a String with s[0].
- What are the two variants of Result?