Skip to content
RustLearn

Module 04 Exercises — Ownership

How to use this page

Attempt every exercise in a real Cargo project before opening a solution — a solution you have not fought for teaches almost nothing. Tick the boxes as you go; progress is saved in this browser.

Before you start, you should be able to say out loud, for any line of code, whether a value moved and whether the original is still usable.

The most valuable exercise here is the prediction drill: guess "compiles" or "error" before running it. Getting a prediction wrong and then reading E0382 is worth ten times more than reading a correct answer. If more than one or two predictions surprise you, re-read §4.3 before moving on — module 05 will not make sense otherwise.

Part A — Warm-Up Drills

Short reps on the mechanics. Do them until the syntax stops costing you any thought.

🟢 Exercise 4.1 — Predict and verify

For each snippet, predict "compiles" or "error", and if it errors, name the reason. Then check with the compiler.

rust
// A
let a = String::from("x"); let b = a; println!("{a}");
// B
let a = 5; let b = a; println!("{a}");
// C
let a = String::from("x"); let b = a.clone(); println!("{a}{b}");
// D
let a = vec![1, 2]; let b = a; println!("{b:?}");
// E
let a = (1, String::from("x")); let b = a; println!("{}", a.0);
Answers
  • A: error E0382 — String moved.
  • B: compiles — i32 is Copy.
  • C: compiles — deep copy.
  • D: compiles — a moved but only b is used.
  • E: error — the tuple isn't Copy (contains String), so the whole tuple moved; even a.0 is unusable.

🟢 Exercise 4.2 — Fix the move

Make this compile in three different ways (clone; return the value; borrow — you may peek ahead for the third).

rust
fn print_it(s: String) { println!("{s}"); }

fn main() {
    let s = String::from("hello");
    print_it(s);
    println!("{s}");
}
Solutions
rust
// 1. clone
print_it(s.clone());

// 2. give it back
fn print_it(s: String) -> String { println!("{s}"); s }
let s = print_it(s);

// 3. borrow (best)
fn print_it(s: &str) { println!("{s}"); }
print_it(&s);

Part B — Core Exercises

The real practice. Attempt each one fully — compiler errors included — before opening a solution.

🟡 Exercise 4.3 — Drop order

Predict the exact output:

rust
struct D(&'static str);
impl Drop for D { fn drop(&mut self) { println!("drop {}", self.0); } }

fn main() {
    let _x = D("x");
    let _y = D("y");
    let z = D("z");
    drop(z);
    println!("end of main");
}
Answer
drop z
end of main
drop y
drop x

z is dropped explicitly; the rest drop in reverse declaration order at scope end.

🟡 Exercise 4.4 — Ownership trace

Add a comment on every line saying who owns the String at that point and whether any binding is invalid.

rust
fn consume(v: Vec<String>) -> usize { v.len() }

fn main() {
    let a = String::from("one");
    let b = String::from("two");
    let list = vec![a, b];
    let n = consume(list);
    println!("{n}");
}
Answer
rust
let a = String::from("one");   // a owns "one"
let b = String::from("two");   // b owns "two"
let list = vec![a, b];         // both moved INTO the Vec; a and b now invalid
let n = consume(list);         // list moved into `consume`; list now invalid
                               // at end of consume, the Vec and both Strings are dropped
println!("{n}");               // n is usize (Copy) — fine

🟡 Exercise 4.5 — Make a type Copy

Define struct Rgb { r: u8, g: u8, b: u8 } and make it Copy. Then add a String name field and explain the compiler error you now get when deriving Copy.

Answer
rust
#[derive(Debug, Clone, Copy)]
struct Rgb { r: u8, g: u8, b: u8 }

Adding name: String gives:

error[E0204]: the trait `Copy` cannot be implemented for this type
  |
  | name: String,
  | ------------ this field does not implement `Copy`

String owns a heap allocation with a destructor; bit-copying it would create two owners of one buffer.

Part C — Challenges

Longer builds. Expect to fight the borrow checker here; that fight is the lesson.

🔴 Exercise 4.6 — Build a resource guard

Write a struct Connection { id: u32 } that prints opening {id} in a new associated function and closing {id} in Drop. Then write a main that opens three connections, closes one early with drop, panics inside a nested scope with std::panic::catch_unwind, and observe that destructors still run during unwinding.

Solution
rust
struct Connection { id: u32 }

impl Connection {
    fn new(id: u32) -> Self { println!("opening {id}"); Connection { id } }
}
impl Drop for Connection {
    fn drop(&mut self) { println!("closing {}", self.id); }
}

fn main() {
    let _a = Connection::new(1);
    let b = Connection::new(2);
    drop(b);

    let _ = std::panic::catch_unwind(|| {
        let _c = Connection::new(3);
        panic!("boom");
    });

    println!("still running");
}

Output shows closing 3 before still running — RAII holds even through a panic. This is why Rust needs no finally.

Self-check

  1. State the three ownership rules from memory.
  2. What exactly is copied during a move of a String?
  3. Why can a type not be both Copy and Drop?
  4. In what order are values dropped in a scope?
  5. Why does Rust need no garbage collector?
Answers
  1. Each value has one owner; only one owner at a time; the value is dropped when the owner leaves scope.
  2. The three stack words (pointer, length, capacity). The heap buffer is not copied; the source binding is invalidated.
  3. Copy means duplication is a meaningless bit-copy; Drop means destruction is meaningful. Two bit-identical copies would both run the destructor → double free.
  4. Reverse declaration order, innermost scope first.
  5. Because the compiler statically knows the single point at which each value dies, and inserts the free there.

Next: Module 05 — Borrowing, References & Slices