Brainbotox · Lessons · Exams

Rust Fundamentals for Beginners: Ownership, Types and Cargo

by lazizanie · Programming · Rust · English

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

CommandWhat it does
cargo newCreates a project with Cargo.toml and src/main.rs
cargo checkType-checks quickly without producing a binary
cargo buildCompiles in debug mode
cargo build --releaseCompiles with optimisations
cargo runBuilds and runs
cargo testRuns the tests
A crate is a unit of compilation: a binary or a library. Dependencies are crates downloaded from crates.io and listed in Cargo.toml.
Install and update Rust with rustup. Format with cargo fmt and lint with cargo clippy. Read compiler errors carefully: they usually explain the fix.

Check yourself

  1. How does Rust manage memory?
  2. What is Cargo?
  3. Why does println! end with an exclamation mark?
  4. Which command type-checks code quickly without building a binary?
  5. What is a crate?
  6. Which flag produces an optimised build?

Take the quiz on Brainbotox

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

FamilyTypesDefault
Signed integersi8 i16 i32 i64 i128 isizei32
Unsigned integersu8 u16 u32 u64 u128 usize
Floatsf32 f64f64
Booleanbool
Characterchar: 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
Integer overflow panics in debug builds and wraps around in release builds. Use checked_add, wrapping_add or saturating_add to state what you want.
Accessing an array out of bounds panics at run time. Rust never reads invalid memory silently.

Check yourself

  1. What is true of a variable declared with let x = 5; in Rust?
  2. What is shadowing?
  3. What is the default integer type in Rust?
  4. How do you convert an i32 to f64?
  5. What happens on integer overflow in a debug build?
  6. How large is a Rust char?

Take the quiz on Brainbotox

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
}
Adding a semicolon (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

  1. What does fn add(a: i32, b: i32) -> i32 { a + b } return?
  2. Which values does for i in 0..3 produce?
  3. In Rust, if can be used on the right side of let to produce a value.
  4. What must a match expression be?
  5. Which loop can return a value through break?
  6. What is ()?

Take the quiz on Brainbotox

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

  1. Each value has an owner.
  2. There is only one owner at a time.
  3. 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 valid

Passing 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

At any time you can have either any number of shared references (&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 string

Check yourself

  1. After let s2 = s1; where s1 is a String, what is true?
  2. When is a value dropped?
  3. How many mutable references to a value can exist at once?
  4. Which type is copied, not moved, on assignment?
  5. What does passing &text to a function do?
  6. How do you make an explicit deep copy of a String?

Take the quiz on Brainbotox

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());
ReceiverMeaning
&selfReads the value
&mut selfModifies the value
selfTakes 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.
Add #[derive(Debug)] above a struct or enum to print it with {:?}.

Check yourself

  1. How does Rust represent a value that may be absent?
  2. Which method receiver allows modifying the struct?
  3. How is an associated function such as new called?
  4. Rust enum variants can carry data.
  5. What does if let Some(x) = value do?
  6. What does #[derive(Debug)] enable?

Take the quiz on Brainbotox

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

TypeWhat it is
StringOwned, growable, heap-allocated UTF-8 text
&strA 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}!");
You cannot index a string with 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

  1. What does v.get(10) return on a Vec with three elements?
  2. What is the difference between String and &str?
  3. What does the ? operator do on an Err value?
  4. What does unwrap() do on None or Err?
  5. You can read the first character of a String with s[0].
  6. What are the two variants of Result?

Take the quiz on Brainbotox