Brainbotox · Lessons · Exams

Rust Interview Questions, Intermediate: Borrowing, Lifetimes, Traits (30 questions)

by lazizanie · University · Programming · Rust · English

30 intermediate Rust interview questions with model answers: ownership and borrowing, Option and Result, error handling, traits and generics, iterators, closures, smart pointers and lifetimes.

Take this exam on Brainbotox, with marking →

30 questions. The model answers are folded under each one.

Question 1

Q1. The borrow checker. This code does not compile. Explain the error, say what real bug the compiler is preventing, and give two ways to fix it.

let mut v = vec![1, 2, 3];
let first = &v[0];
v.push(4);
println!("{}", first);
Model answer

The error: cannot borrow v as mutable because it is also borrowed as immutable.

  • first is a shared (immutable) reference into v.
  • v.push(4) needs an exclusive (mutable) reference to v.
  • first is still used afterwards by println!, so both borrows are alive at the same time.
Rust's rule: at any moment, either any number of shared references or exactly one mutable reference, never both.

The bug prevented: push may need more room and reallocate the vector's buffer. The old buffer is freed, and first would point to freed memory: a dangling reference. In C++ this compiles and is undefined behaviour.

Fix 1: copy the value. i32 is Copy, so no borrow is kept.

let first = v[0];
v.push(4);
println!("{}", first);

Fix 2: end the borrow before mutating. A borrow lasts until its last use, not until the end of the block.

let first = &v[0];
println!("{}", first);
v.push(4);

Revise: Rust Intermediate for Confirmed Developers: Traits and Lifetimes

Question 2

Q2. Lifetimes. This function does not compile.

fn longest(a: &str, b: &str) -> &str {
    if a.len() > b.len() { a } else { b }
}

(a) Why does the compiler reject it?

(b) Write the correct signature.

(c) What does the lifetime you added actually mean? Does it change how long the strings live?

Model answer

(a) Why: missing lifetime specifier. The function returns a reference, and the compiler must know which input it borrows from, so that callers cannot use the result after that input is gone. With two reference parameters the lifetime elision rules cannot choose, and the body may return either one.

(b) Correct signature:

fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() > b.len() { a } else { b }
}

(c) Meaning: there is some lifetime 'a for which both inputs are valid, and the result is valid for that same 'a. In practice the result may be used only as long as both arguments are still alive, that is for the shorter of the two.

It changes nothing at run time. Lifetimes do not extend or shorten how long a value lives. They are a description the compiler checks at each call site.

let a = String::from("long string");
let res;
{
    let b = String::from("hi");
    res = longest(&a, &b);
} // b dropped here
println!("{}", res); // error: b does not live long enough
What a strong candidate adds: if the function always returned a, only a and the result would need 'a, and b could have its own lifetime.

Revise: Rust Intermediate for Confirmed Developers: Traits and Lifetimes

Question 3

Q3. Static and dynamic dispatch.

trait Shape { fn area(&self) -> f64; }
fn print_a(s: &impl Shape) { println!("{}", s.area()); }
fn print_b(s: &dyn Shape)  { println!("{}", s.area()); }

(a) What is the difference between print_a and print_b in how the call to area is resolved?

(b) Give one advantage of each.

(c) You need one list holding circles and squares together. Which form do you use, and how do you write the type?

Model answer

(a) How the call is resolved

  • &impl Shape is a generic: it is short for fn print_a<T: Shape>(s: &T). The compiler generates one copy of the function per concrete type used (monomorphization) and the call to area is fixed at compile time: static dispatch.
  • &dyn Shape is a trait object: a pointer to the data plus a pointer to a table of methods (vtable). One function exists, and area is looked up in the table at run time: dynamic dispatch.

(b) Advantages

  • Static: fastest. No lookup, and the call can be inlined. The cost is longer compile times and a larger binary.
  • Dynamic: one compiled function, smaller binary, and different concrete types can be handled through the same type. The cost is an indirect call that cannot be inlined.

(c) Mixed list: dynamic dispatch. A Vec<T> holds one type only, and trait objects have no known size, so they go behind a pointer:

let shapes: Vec<Box<dyn Shape>> = vec![
    Box::new(Circle { r: 1.0 }),
    Box::new(Square { side: 2.0 }),
];
for s in &shapes {
    println!("{}", s.area());
}
What a strong candidate adds: an enum Shape { Circle(..), Square(..) } is a third option when the set of types is closed, with no heap allocation. Not every trait can be made into a trait object: methods that are generic or return Self prevent it.

Revise: Rust Intermediate for Confirmed Developers: Traits and Lifetimes

Question 4

Q4. Moves. The first snippet does not compile and the second does. Explain why.

let s1 = String::from("hi");
let s2 = s1;
println!("{}", s1);        // error
let n1 = 5;
let n2 = n1;
println!("{}", n1);        // fine
Model answer

Every value in Rust has one owner.

  • A String owns a heap buffer. let s2 = s1; moves ownership to s2: only the pointer, length and capacity are copied, and s1 becomes invalid. Using it is a compile error: borrow of moved value. This prevents two owners from freeing the same buffer.
  • An i32 implements the Copy trait. Assignment copies the bits and both variables stay valid, because there is nothing to free.

To keep both strings usable:

let s2 = s1.clone();   // a real copy of the heap data
let s3 = &s1;          // or borrow, with no copy

A move also happens when a value is passed to a function or returned from one.

Question 5

Q5. Copy and Clone. What is the difference between the Copy and Clone traits? Can a struct containing a String be Copy?

Model answer
  • Clone is an explicit copy: you call .clone(). It may be expensive, for example allocating a new buffer for a String or Vec.
  • Copy is an implicit, bitwise copy done on assignment and when passing by value. It must be cheap and has no custom code. It is a marker trait, and it requires Clone.

A type can be Copy only if all its fields are Copy and it does not implement Drop. Integers, floats, bool, char, shared references &T, and tuples or arrays of those are Copy.

A struct holding a String cannot be Copy: copying the bits would give two owners of one heap buffer and a double free. It can be Clone.

#[derive(Clone, Copy)]
struct Point { x: f64, y: f64 }      // fine
#[derive(Clone)]
struct User { name: String }         // Clone only

Note that &mut T is not Copy, since two copies would break exclusivity.

Question 6

Q6. String and &str. What is the difference between String and &str? How do you convert between them?

Model answer
  • String is an owned, growable, heap-allocated UTF-8 buffer: pointer, length, capacity. It frees its memory when dropped.
  • &str is a borrowed view (a string slice) of UTF-8 bytes owned by someone else: pointer and length. It can point into a String, into a string literal stored in the binary (&'static str), or into any other bytes.
let owned: String = String::from("hello");   // or "hello".to_string()
let view: &str = &owned;                     // free: no copy
let part: &str = &owned[0..2];               // "he"
let again: String = view.to_owned();         // allocates and copies

&str to String allocates; String to &str is free.

Both are always valid UTF-8, so indexing by integer (s[0]) is not allowed: a character may take 1 to 4 bytes. Slicing in the middle of a character panics. Use .chars() or .bytes() to iterate.

Question 7

Q7. Function parameters. Which signature is best for a function that only reads a string, and why?

fn greet_a(name: String)
fn greet_b(name: &String)
fn greet_c(name: &str)
Model answer

fn greet_c(name: &str).

  • greet_a(String) takes ownership. The caller loses its string or must clone() it, an allocation for nothing. Right only when the function needs to keep or consume the string.
  • greet_b(&String) borrows, but only accepts a String. A caller with a literal must allocate one first.
  • greet_c(&str) accepts everything: a literal, a slice, and a &String, which is converted automatically by deref coercion.
let s = String::from("Ada");
greet_c(&s);          // &String becomes &str
greet_c("Grace");     // literal
greet_c(&s[..2]);     // slice

The same rule applies elsewhere: take &[T], not &Vec<T>, and &Path, not &PathBuf. Borrow the most general view of what you need.

Question 8

Q8. Mutable borrows. Why does this not compile? What is the rule, and what does it protect against?

let mut s = String::from("a");
let r1 = &mut s;
let r2 = &mut s;
r1.push('b');
r2.push('c');
Model answer

Error: cannot borrow s as mutable more than once at a time.

At any moment a value has either one mutable reference or any number of shared references, never both.

r1 is still used after r2 is created, so two mutable references are alive together.

What the rule prevents, at compile time:

  • data races between threads;
  • invalidated references in one thread: one reference reallocates a buffer while another still points into the old one;
  • it also lets the compiler optimise, since a &mut is known to be the only way to reach the data.

Fixes: use the references one after the other, since a borrow ends at its last use.

let r1 = &mut s;
r1.push('b');          // last use of r1
let r2 = &mut s;       // fine now
r2.push('c');

To mutate two parts of one collection at once, use methods designed for it: split_at_mut, iter_mut, or borrow two different fields of a struct.

Question 9

Q9. Option. fn find_user(id: u32) -> Option<User>. Show four ways to handle the result and say when each is appropriate.

Model answer
// 1. match: handle both cases explicitly
match find_user(7) {
    Some(u) => println!("{}", u.name),
    None => println!("not found"),
}
// 2. if let / let else: only one case matters
if let Some(u) = find_user(7) {
    println!("{}", u.name);
}
let Some(u) = find_user(7) else { return; };
// 3. combinators: transform or give a default
let name = find_user(7)
    .map(|u| u.name)
    .unwrap_or_else(|| "guest".to_string());
// 4. ? : pass None up to the caller
fn user_name(id: u32) -> Option<String> {
    let u = find_user(id)?;
    Some(u.name)
}
  • unwrap() and expect("msg") panic on None. Keep them for tests, prototypes, and cases that really cannot fail. Prefer expect with a message that says why.
  • ok_or(err) converts an Option into a Result when absence is an error.

Rust has no null. Option makes "may be absent" part of the type, and the compiler forces the caller to deal with it.

Question 10

Q10. The ? operator. What does ? do in this function? What is it shorthand for, and why can two different error types be used with one return type?

fn read_number(path: &str) -> Result<i32, Box<dyn std::error::Error>> {
    let text = std::fs::read_to_string(path)?;
    let n = text.trim().parse::<i32>()?;
    Ok(n)
}
Model answer

On a Result, ? means: if it is Ok(v), give me v; if it is Err(e), return the error from the function now.

It is roughly:

let text = match std::fs::read_to_string(path) {
    Ok(v) => v,
    Err(e) => return Err(From::from(e)),
};

The From::from(e) is the key detail: ? converts the error into the function's error type.

  • read_to_string fails with std::io::Error.
  • parse fails with ParseIntError.

Both implement the Error trait, and any such type converts into Box<dyn Error>, so both work with the same return type.

Rules: ? can only be used in a function that returns Result or Option (or another compatible type), and the error must be convertible with From. For your own error enum, implement From<io::Error> and so on, or derive it with the thiserror crate.

Question 11

Q11. Error types. How do you design the error type of a library, and how is that different in an application? Where do thiserror and anyhow fit?

Model answer

Library: callers need to match on what went wrong, so give them a concrete type, usually an enum.

#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    #[error("cannot read {path}")]
    Io { path: String, #[source] source: std::io::Error },
    #[error("invalid value for {0}")]
    Invalid(String),
}

thiserror generates the Display, Error and From implementations you would otherwise write by hand. It adds nothing to your public API.

Application: most errors are only logged or shown to the user, with context. One flexible type is enough.

use anyhow::{Context, Result};
fn load() -> Result<Config> {
    let text = std::fs::read_to_string("app.toml")
        .context("reading app.toml")?;
    Ok(toml::from_str(&text)?)
}

anyhow::Error holds any error, adds context and a backtrace. It is the convenient form of Box<dyn Error>.

Rule: thiserror for libraries, anyhow for binaries. Do not expose anyhow::Error in a library's public API, because callers could not match on it.

Question 12

Q12. panic or Result. When should a Rust function panic, and when should it return a Result? Is unwrap() acceptable in production code?

Model answer
  • Result for failures that can happen in a correct program: a missing file, invalid user input, a network timeout. The caller decides what to do.
  • panic! for bugs: a broken invariant, an index that should always be valid, a state that is supposed to be impossible. There is nothing sensible the caller could do.

A panic unwinds the stack of the current thread and runs destructors (or aborts the process if panic = "abort"). It is not a control flow tool.

unwrap() in production:

  • Not on anything that depends on input, I/O or the environment.
  • Acceptable when failure is truly impossible and you can say why. Then expect is better, because the message documents the reasoning:
let re = Regex::new(r"^\d+$").expect("static regex is valid");
  • Fine in tests and examples.

A library should almost never panic on bad input: return an error and let the application choose.

Question 13

Q13. Pattern matching. What does it mean that match is exhaustive? Rewrite this with if let, and then with let else.

match config.get("port") {
    Some(p) => start(p),
    None => {}
}
Model answer

Exhaustive means the compiler checks that every possible value is covered. If you add a variant to an enum, every match on it that has no wildcard stops compiling until you handle the new case. This is a major safety feature: avoid _ => on your own enums when you want that check.

With if let, for when only one pattern matters:

if let Some(p) = config.get("port") {
    start(p);
}

With let else, for when the other case should leave early, which keeps the main path unindented:

let Some(p) = config.get("port") else {
    return;
};
start(p);

The else block must diverge: return, break, continue or panic!.

Patterns can also bind, test and destructure at once:

match point {
    (0, 0) => "origin",
    (x, 0) if x > 0 => "positive x axis",
    (_, _) => "elsewhere",
}

Question 14

Q14. Enums with data. Define a Shape type that is either a circle with a radius or a rectangle with a width and height, and write area. How does this compare with a class hierarchy?

Model answer
enum Shape {
    Circle(f64),
    Rect { w: f64, h: f64 },
}
impl Shape {
    fn area(&self) -> f64 {
        match self {
            Shape::Circle(r) => std::f64::consts::PI * r * r,
            Shape::Rect { w, h } => w * h,
        }
    }
}

A Rust enum is a sum type: a value is exactly one of the variants, and each variant can carry its own data. Option<T> and Result<T, E> are ordinary enums.

Compared with a class hierarchy:

  • The set of variants is closed and known to the compiler, so match is checked for exhaustiveness. Adding a variant shows every place to update.
  • Adding a new operation is easy: write another function with a match. With classes, that means touching every class.
  • Adding a new variant from outside the crate is not possible. For an open set of types, use a trait.
  • No heap allocation or dynamic dispatch is needed: the enum is as large as its biggest variant plus a tag.

Question 15

Q15. Method receivers. Explain the difference between self, &self and &mut self as the first parameter of a method. What is a function without self called?

Model answer
  • &self: borrows the value immutably. The method can read it. The most common form.
  • &mut self: borrows it mutably. The method can change it. The caller's variable must be mut.
  • self: takes ownership. The value is moved into the method and cannot be used afterwards. Used for conversions and builders.
impl Buffer {
    fn new() -> Self { Buffer { data: Vec::new() } }  // associated function
    fn len(&self) -> usize { self.data.len() }
    fn push(&mut self, b: u8) { self.data.push(b); }
    fn into_vec(self) -> Vec<u8> { self.data }
}
let mut buf = Buffer::new();
buf.push(1);
let v = buf.into_vec();
// buf can no longer be used here

A function in an impl block with no self is an associated function, called with Type::name(). new is a convention, not a keyword.

Naming conventions follow the receiver: as_x borrows cheaply, to_x makes a copy, into_x consumes.

Question 16

Q16. Traits. What is a trait? Write a trait Describe with one required method and one default method, implement it for a struct, and write a function that accepts any type implementing it.

Model answer

A trait defines behaviour that types can share: a set of methods a type must provide. It plays the role of an interface, and can also supply default code.

trait Describe {
    fn name(&self) -> String;                 // required
    fn describe(&self) -> String {            // default
        format!("This is {}", self.name())
    }
}
struct Dog;
impl Describe for Dog {
    fn name(&self) -> String { "a dog".to_string() }
}
fn show(item: &impl Describe) {
    println!("{}", item.describe());
}

The last function can also be written with an explicit bound, which is needed when several parameters must be the same type or the bounds get long:

fn show<T: Describe>(item: &T) { ... }
fn show<T>(item: &T)
where
    T: Describe + Clone,
{ ... }

Differences from interfaces in other languages: you can implement your trait for a type you did not write (even i32), and traits can have associated types and constants.

Question 17

Q17. Derive. What does #[derive(Debug, Clone, PartialEq, Eq, Hash)] generate? Which traits must a type have to be a HashMap key, and why can a struct with an f64 field not be one?

Model answer

derive asks the compiler to write a standard implementation, field by field:

  • Debug: formatting with {:?}, for logs and test output.
  • Clone: .clone(), which clones each field.
  • PartialEq: == and !=, comparing each field.
  • Eq: a marker saying equality is total: every value equals itself.
  • Hash: a hash computed from all fields.

Each derive requires that every field already implements the trait.

A HashMap key needs Eq and Hash, and they must agree: equal keys must have equal hashes.

f64 implements PartialEq but not Eq or Hash, because NaN != NaN: a value that is not equal to itself would break a hash table. So a struct with an f64 field cannot derive them. Options: key on an integer representation (cents instead of dollars), or use a wrapper such as the ordered-float crate.

Other common derives: Default, PartialOrd, Ord, Copy.

Question 18

Q18. Generics with bounds. This function does not compile. Why? Fix it.

fn largest<T>(items: &[T]) -> T {
    let mut max = items[0];
    for &item in items {
        if item > max {
            max = item;
        }
    }
    max
}
Model answer

Two things are missing. With a bare T, the compiler knows nothing about the type:

  1. item > max needs the comparison operators, which come from the PartialOrd trait.
  2. let mut max = items[0] and for &item move values out of a borrowed slice. That is only allowed if the values can be copied, so T must be Copy.
fn largest<T: PartialOrd + Copy>(items: &[T]) -> T {
    let mut max = items[0];
    for &item in items {
        if item > max {
            max = item;
        }
    }
    max
}

Rust checks generic code once, against its bounds, not against each type it is later used with. So the body may only use what the bounds promise.

A more general version avoids requiring Copy by returning a reference, so it also works for String:

fn largest<T: PartialOrd>(items: &[T]) -> &T {
    let mut max = &items[0];
    for item in items {
        if item > max { max = item; }
    }
    max
}

Both panic on an empty slice. Returning Option<&T> is the complete answer.

Question 19

Q19. Three ways to iterate. For let v = vec![String::from("a"), String::from("b")];, what is the item type in each loop, and can v be used afterwards?

for x in v.iter() { }
for x in v.iter_mut() { }
for x in v.into_iter() { }
Model answer
CallItem typeEffect on v
v.iter()&Stringborrowed, usable afterwards
v.iter_mut()&mut Stringborrowed mutably (needs let mut v), usable afterwards
v.into_iter()Stringconsumed: v is moved and gone

The for loop calls into_iter() on whatever you give it, so the short forms are:

for x in &v { }       // same as v.iter()
for x in &mut v { }   // same as v.iter_mut()
for x in v { }        // same as v.into_iter(), consumes v

Choose by what you need: read the items, change them in place, or take ownership of them (for example to move the strings into another collection without cloning).

Question 20

Q20. Lazy iterators. What does this print?

let v = vec![1, 2, 3];
v.iter().map(|x| println!("{}", x));
Model answer

Nothing. The compiler also warns: unused Map that must be used, iterators are lazy and do nothing unless consumed.

Iterator adaptors such as map, filter, take and zip only build a description of the work. Nothing runs until a consumer asks for items: collect, sum, count, for_each, fold, find, or a for loop.

v.iter().for_each(|x| println!("{}", x));   // runs
for x in &v { println!("{}", x); }          // clearer for side effects
let doubled: Vec<i32> = v.iter().map(|x| x * 2).collect();

Laziness is what makes chains efficient: the items flow through the whole chain one at a time, with no intermediate collections, and the compiler usually turns the chain into a single loop as fast as a hand-written one.

It also allows infinite iterators: (1..).filter(|n| n % 7 == 0).take(3) stops after three items.

Question 21

Q21. Closures. What are Fn, FnMut and FnOnce? What does the move keyword do, and why is it needed with thread::spawn?

Model answer

A closure captures variables from its environment. The compiler picks the least restrictive capture it can, and that decides which traits the closure implements:

  • Fn: only reads what it captured. Can be called many times, even concurrently.
  • FnMut: modifies what it captured. Can be called many times, but needs exclusive access.
  • FnOnce: consumes something it captured (moves it out). Can be called only once.

Every closure is FnOnce; those that do not consume are also FnMut; those that do not mutate are also Fn.

let name = String::from("Ada");
let greet = || println!("hi {}", name);        // Fn: borrows name
let mut count = 0;
let mut inc = || count += 1;                   // FnMut
let consume = move || drop(name);              // FnOnce

move forces the closure to take ownership of what it captures instead of borrowing.

With thread::spawn, the new thread may outlive the function that created it. A borrowed local could be freed while the thread still uses it, so the compiler requires the closure to own its data ('static):

let data = vec![1, 2, 3];
std::thread::spawn(move || println!("{:?}", data));

Question 22

Q22. Box. What is Box<T>? Give three situations where you need it, and explain why this type does not compile without one.

enum List {
    Cons(i32, List),
    Nil,
}
Model answer

Box<T> is an owning pointer to a value on the heap. The box itself is one pointer wide. When the box goes out of scope, the value is dropped and the memory freed. There is exactly one owner.

The enum fails with: recursive type has infinite size. A List would contain a List, which contains a List, and so on, so the compiler cannot compute its size. A box has a known size, which breaks the recursion:

enum List {
    Cons(i32, Box<List>),
    Nil,
}

When you need a box:

  1. Recursive types: lists, trees, expression trees.
  2. Trait objects: Box<dyn Trait>, to own a value whose concrete type is only known at run time, for example Vec<Box<dyn Shape>> or Box<dyn Error>.
  3. Large values: to move a big struct cheaply (only the pointer moves) or to keep it off the stack.

Do not box by habit: values live on the stack by default in Rust, and Vec and String already put their contents on the heap.

Question 23

Q23. Rc and RefCell. What problems do Rc<T> and RefCell<T> solve? What happens when this runs?

use std::cell::RefCell;
let c = RefCell::new(5);
let a = c.borrow_mut();
let b = c.borrow_mut();
Model answer
  • Rc<T> gives shared ownership: several owners of one value, with a reference count. The value is dropped when the last Rc goes away. It only hands out shared access, so the value is read-only.
  • RefCell<T> gives interior mutability: it lets you mutate a value through a shared reference by checking the borrow rules at run time instead of at compile time.

Together, Rc<RefCell<T>> is a value with several owners that can still be modified, used for graphs and shared state in single-threaded code.

The snippet compiles and then panics on the third line: already borrowed, BorrowMutError. The rule is the same as always, one mutable borrow or many shared ones, but a violation is found at run time.

Avoid the panic by keeping borrows short, or use try_borrow_mut(), which returns a Result.

Both types are single-threaded. Across threads, use Arc<Mutex<T>>. Reach for these only when plain ownership and borrowing really cannot express the design.

Question 24

Q24. Reference cycles. Can safe Rust leak memory? Explain how two Rc values can keep each other alive and how Weak fixes it.

Model answer

Yes. Rust guarantees memory safety, not the absence of leaks.

Rc frees its value when the strong count reaches zero. If A holds an Rc to B and B holds an Rc to A, each count stays at 1 after all outside references are gone. Neither is ever dropped.

Weak<T> is a reference that does not keep the value alive. It does not count as an owner. To use it you call upgrade(), which returns Option<Rc<T>>: None if the value has been dropped.

use std::cell::RefCell;
use std::rc::{Rc, Weak};
struct Node {
    parent: RefCell<Weak<Node>>,       // does not own the parent
    children: RefCell<Vec<Rc<Node>>>,  // owns the children
}
let child = Rc::new(Node { /* ... */ });
*child.parent.borrow_mut() = Rc::downgrade(&parent);
if let Some(p) = child.parent.borrow().upgrade() {
    // parent is still alive
}

Design rule: ownership goes one way (parent owns children). Back references are weak. Many Rust programs avoid the problem entirely by storing nodes in a Vec and referring to them by index.

Question 25

Q25. Lifetimes in structs. What does the lifetime on this struct mean? Why does the usage below fail to compile?

struct Parser<'a> {
    input: &'a str,
}
fn make() -> Parser<'static> {
    let text = String::from("abc");
    Parser { input: &text }
}
Model answer

Parser<'a> holds a reference, so it does not own its text. The lifetime parameter says: a Parser cannot outlive the string it borrows from. Any struct that stores a reference needs one.

The function fails with: text does not live long enough.

  • text is a local String. It is dropped when make returns.
  • The returned Parser would hold a reference to freed memory.
  • The signature also claims 'static, valid for the whole program, which a local cannot satisfy.

Fixes:

// 1. Borrow from the caller, who keeps the string alive
fn make(text: &str) -> Parser<'_> {
    Parser { input: text }
}
// 2. Own the data: no lifetime needed
struct OwnedParser {
    input: String,
}

Guideline: structs that live a long time or cross threads usually own their data. Borrowing structs are for short-lived views, such as parsers and iterators, where avoiding a copy matters.

Question 26

Q26. 'static. What does 'static mean in &'static str, and what does it mean in the bound T: 'static? Does T: 'static mean the value lives for ever?

Model answer

Two related meanings.

1. &'static T: a reference valid for the whole program. The data it points to is never freed. String literals are the usual case: they are stored in the binary.

let s: &'static str = "hello";

2. T: 'static: the type contains no borrowed data that could expire (other than 'static references). It is a bound on the type, not a statement about how long a value lives.

It does not mean the value lives for ever. A String, a Vec<u8> and an i32 are all 'static: they own their data. You can create one and drop it a moment later.

Where it appears:

pub fn spawn<F>(f: F) where F: FnOnce() + Send + 'static

The thread may outlive the caller, so the closure must not hold references to the caller's locals. Owned data passes. &local does not.

Common mistake: seeing an error that mentions 'static and adding &'static everywhere. The usual fix is to pass owned data: clone it, move it, or wrap it in an Arc.

Question 27

Q27. Arrays, vectors and slices. What is the difference between [i32; 3], Vec<i32> and &[i32]? Which should a function that sums numbers accept?

Model answer
  • [i32; 3] is an array: a fixed size known at compile time, part of the type. Stored inline, usually on the stack. No allocation.
  • Vec<i32> is a vector: an owned, growable buffer on the heap (pointer, length, capacity).
  • &[i32] is a slice: a borrowed view of a run of elements owned by something else (pointer and length). It can point into an array, a vector, or part of either.

The function should accept &[i32]:

fn sum(xs: &[i32]) -> i32 {
    xs.iter().sum()
}
let a = [1, 2, 3];
let v = vec![4, 5, 6];
sum(&a);          // array
sum(&v);          // &Vec<i32> coerces to &[i32]
sum(&v[1..]);     // part of a vector

Taking &Vec<i32> would reject arrays and sub-slices for no benefit, and taking Vec<i32> would take ownership and force callers to clone.

Use &mut [T] to modify elements in place, and &mut Vec<T> only when the function must change the length.

Question 28

Q28. The entry API. Write a function that counts how many times each word appears in a text, using a HashMap. Why is the entry API better than contains_key followed by insert?

Model answer
use std::collections::HashMap;
fn count_words(text: &str) -> HashMap<&str, usize> {
    let mut counts = HashMap::new();
    for word in text.split_whitespace() {
        *counts.entry(word).or_insert(0) += 1;
    }
    counts
}

entry(key) returns a handle to the slot for that key, whether it exists or not. or_insert(0) inserts 0 if it was empty and returns a &mut to the value, which is then incremented.

Why it is better than checking first:

  • One lookup instead of two or three: the key is hashed once.
  • It is one expression, with no gap between the check and the insert.
  • It satisfies the borrow checker cleanly. The naive version that holds a reference from get_mut and then calls insert in the other branch is a classic borrow error.

Related methods: or_default(), or_insert_with(|| expensive()) which builds the value only when needed, and and_modify(|v| *v += 1).or_insert(1).

The keys here are &str slices borrowed from text, so no word is copied. The map cannot outlive the text.

Question 29

Q29. Modules and visibility. What is the difference between a package, a crate and a module? What do pub, pub(crate) and no modifier mean?

Model answer
  • A package is what Cargo manages: a Cargo.toml plus one or more crates.
  • A crate is one compilation unit: a library (src/lib.rs) or a binary (src/main.rs). It is what other code depends on.
  • A module (mod) is a namespace inside a crate, used to organise code and control visibility. It can be inline or in its own file.

Visibility: everything is private by default.

  • No modifier: visible in the current module and its child modules only.
  • pub(crate): visible anywhere inside this crate, but not to users of the crate.
  • pub: part of the public API, if every module on the path is also public.
  • pub(super): visible in the parent module.
mod db {
    pub struct Pool {
        pub size: u32,
        conn: Vec<Conn>,          // private field
    }
    pub(crate) fn connect() -> Pool { ... }
    fn helper() { }               // private
}
use crate::db::Pool;

Struct fields have their own visibility. A struct with a private field cannot be built from outside its module, which is how invariants are protected: outsiders must go through a constructor.

Question 30

Q30. Drop and RAII. What does this print? What is RAII, and how do you release a value early?

struct D(&'static str);
impl Drop for D {
    fn drop(&mut self) {
        println!("drop {}", self.0);
    }
}
fn main() {
    let _a = D("a");
    let _b = D("b");
    println!("end");
}
Model answer

It prints end, drop b, drop a.

  • A value is dropped when its owner goes out of scope, here at the end of main, after "end".
  • Local variables are dropped in reverse order of declaration, so _b goes before _a. Later values may depend on earlier ones, so this order is the safe one.

RAII means a resource is tied to the lifetime of a value: acquiring it creates the value, and Drop releases it. This is how Rust closes files, frees memory and unlocks mutexes without a garbage collector and without finally. A MutexGuard unlocks when it goes out of scope, on every path, including early returns and panics.

To release early:

let guard = mutex.lock().unwrap();
// ... use it ...
drop(guard);              // unlocks now
{
    let guard = mutex.lock().unwrap();
}                         // or limit the scope

You cannot call value.drop() yourself. Trap: let _ = D("x"); drops the value immediately, while let _x = D("x"); keeps it until the end of the scope. Writing let _ = mutex.lock(); therefore locks and unlocks at once.