Practice

Rust exercises

Make a change, predict what it will do, and compare the result.

  1. 1

    Rust Basics

    Bind values and print them.

    Adapt the lesson example. Change one value or element, predict the result, and explain why it changes.

    Show starting example
    Rust
    fn main() {
        let name = "Ada";
        println!("Hello, {}", name);
    }
  2. 2

    Rust Ownership

    Borrow a string without moving it.

    Adapt the lesson example. Change one value or element, predict the result, and explain why it changes.

    Show starting example
    Rust
    fn show(value: &str) {
        println!("{}", value);
    }
    fn main() {
        let name = String::from("Ada");
        show(&name);
        println!("{}", name);
    }
  3. 3

    Rust Variables, Mutability, and Shadowing

    Bindings are immutable by default; mut and shadowing change that.

    Predict the output if the last arithmetic line were let count = count + 1;

    Reveal answer and reasoning

    count is 3 before it, so the new binding is 4 and it prints 4.

    Show starting example
    Rust
    fn main() {
        let mut count = 1;
        count += 2;
        let count = count * 10;
        println!("{}", count);
    }
  4. 4

    Rust Enums and match

    Model alternatives with an enum and handle each one with match.

    Add a Rectangle(u32, u32) variant.

    Reveal answer and reasoning

    Add Rectangle(u32, u32) to the enum and the arm Shape::Rectangle(w, h) => w * h, otherwise match will not compile.

    Show starting example
    Rust
    enum Shape {
        Circle(u32),
        Square(u32),
    }
    
    fn area(shape: &Shape) -> u32 {
        match shape {
            Shape::Circle(r) => 3 * r * r,
            Shape::Square(s) => s * s,
        }
    }
    
    fn main() {
        println!("{}", area(&Shape::Circle(2)));
        println!("{}", area(&Shape::Square(5)));
    }
  5. 5

    Rust Vectors

    Store a growable list with Vec and sum it with an iterator.

    Print the average as a float.

    Reveal answer and reasoning

    Convert both values: total as f64 / scores.len() as f64 gives 86.

    Show starting example
    Rust
    fn main() {
        let mut scores = vec![82, 91, 76];
        scores.push(95);
        let total: i32 = scores.iter().sum();
        println!("{} {}", scores.len(), total);
    }