Skip to content
RustLearn

Module 05 Exercises — Borrowing, References & Slices

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, be able to state the borrowing rules from memory and, more importantly, to explain why the second one exists — the Vec reallocation story in §5.3 is the honest answer.

Many of these drills are designed to fail. When one does, read the error, then try to fix it by shortening a borrow before you reach for .clone(). That instinct is what module 05 is really teaching.

Part A — Warm-Up Drills

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

🟢 Exercise 5.1 — Add the missing muts

Make this compile by adding exactly three muts:

rust
fn append(s: &String) { s.push_str("!"); }

fn main() {
    let s = String::from("hi");
    append(&s);
    println!("{s}");
}
Solution
rust
fn append(s: &mut String) { s.push_str("!"); }

fn main() {
    let mut s = String::from("hi");
    append(&mut s);
    println!("{s}");
}

🟢 Exercise 5.2 — Classify the errors

For each, say which rule is violated:

rust
// A
let mut s = String::from("a");
let r1 = &mut s; let r2 = &mut s; println!("{r1}{r2}");
// B
let mut v = vec![1]; let f = &v[0]; v.push(2); println!("{f}");
// C
fn f() -> &i32 { let x = 5; &x }
// D
let s = String::from("a"); let r = &mut s;
Answers
  • A: two mutable borrows alive at once (E0499).
  • B: mutable borrow (push) while an immutable borrow is live (E0502).
  • C: returning a reference to a local (E0106/E0515) — the referent dies.
  • D: cannot borrow an immutable binding as mutable (E0596) — s needs mut.

Part B — Core Exercises

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

🟡 Exercise 5.3 — Generalize the signatures

Rewrite these to accept the widest possible input without changing behaviour:

rust
fn shout(s: &String) -> String { s.to_uppercase() }
fn total(v: &Vec<i32>) -> i32 { v.iter().sum() }
Solution
rust
fn shout(s: &str) -> String { s.to_uppercase() }
fn total(v: &[i32]) -> i32 { v.iter().sum() }

Now shout("hi") and total(&[1,2,3]) both work, with no allocation forced on callers.

🟡 Exercise 5.4 — last_word

Write fn last_word(s: &str) -> &str returning the final whitespace-separated word (or the whole string if there's no space). Do not allocate. Test with "hello big world", "single", and "".

Solution
rust
fn last_word(s: &str) -> &str {
    match s.rfind(' ') {
        Some(i) => &s[i + 1..],
        None => s,
    }
}

fn main() {
    assert_eq!(last_word("hello big world"), "world");
    assert_eq!(last_word("single"), "single");
    assert_eq!(last_word(""), "");
}

Idiomatic alternative: s.split_whitespace().last().unwrap_or("").

🟡 Exercise 5.5 — Fix without cloning

Make this compile without using clone:

rust
fn main() {
    let mut names = vec![String::from("ada"), String::from("alan")];
    let first = &names[0];
    names.push(String::from("grace"));
    println!("{first}");
}
Solution
rust
fn main() {
    let mut names = vec![String::from("ada"), String::from("alan")];
    println!("{}", &names[0]);          // use the borrow before mutating
    names.push(String::from("grace"));
    println!("{}", names.len());
}

Or reorder: push first, then borrow. The lesson is that a borrow and a reallocation can never overlap.

Part C — Challenges

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

🔴 Exercise 5.6 — In-place operations on slices

Implement, taking &mut [i32] and without allocating:

  1. fn reverse_in_place(xs: &mut [i32])
  2. fn partition_evens(xs: &mut [i32]) -> usize — move all even numbers to the front and return the count of evens (order within groups doesn't matter).
Solution
rust
fn reverse_in_place(xs: &mut [i32]) {
    let (mut i, mut j) = (0usize, xs.len().saturating_sub(1));
    while i < j {
        xs.swap(i, j);
        i += 1;
        j -= 1;
    }
}

fn partition_evens(xs: &mut [i32]) -> usize {
    let mut boundary = 0;
    for i in 0..xs.len() {
        if xs[i] % 2 == 0 {
            xs.swap(i, boundary);
            boundary += 1;
        }
    }
    boundary
}

fn main() {
    let mut a = [1, 2, 3, 4, 5];
    reverse_in_place(&mut a);
    assert_eq!(a, [5, 4, 3, 2, 1]);

    let mut b = [1, 2, 3, 4, 5, 6];
    let n = partition_evens(&mut b);
    assert_eq!(n, 3);
    assert!(b[..n].iter().all(|x| x % 2 == 0));
}

Note xs.swap(i, j) — you can't write let a = &mut xs[i]; let b = &mut xs[j]; because the compiler can't prove i != j. swap and split_at_mut exist precisely for this.

Self-check

  1. State the borrowing rules in one sentence.
  2. What is NLL and how does it change when a borrow ends?
  3. Why should a function take &str instead of &String?
  4. What two words make up a slice at runtime?
  5. Why does v.push(x) conflict with an outstanding &v[0]?
Answers
  1. Either one mutable reference or any number of shared references at a time, and every reference must be valid for as long as it is used.
  2. Non-lexical lifetimes: a borrow ends at its last use rather than at the end of the enclosing block.
  3. &str also accepts string literals and substrings via deref coercion — strictly more callers, no cost.
  4. A pointer and a length.
  5. push may reallocate the buffer, which would leave the existing reference dangling.

Next: Module 06 — Structs & Methods