The bug Rust won't let you write
Worked examples
Read the claim, then run it and check the machine agrees. One at a time — nothing here is taken on trust.
fn describe(name: String) -> String {
format!("hi {name}")
}
fn main() {
let name = String::from("hello");
let msg = describe(name); // ownership moves into describe
// let n = name.len(); // <- uncomment: error[E0382]
// // borrow of moved value: `name`
// Fix A: read the length BEFORE moving.
let a = String::from("world");
let n = a.len(); // borrow, a still owned
let msg2 = describe(a); // now move it
println!("{msg} / {msg2} / len was {n}");
}
The commented line is the use-after-free shape from the C slide,
and it stops the program from existing. Fix A is the cheapest: the
.len() call only borrows, so reading it first leaves a yours
to move afterwards. No allocation, no clone — just ordering. Prints
hi hello / hi world / len was 5.
fn describe(name: String) -> String {
format!("hi {name}")
}
fn main() {
let name = String::from("hello");
let msg = describe(name.clone()); // give describe its OWN copy
let n = name.len(); // original still owned here
println!("{msg}, and name is still {n} bytes: {name}");
}
When you genuinely need the value in two places, clone() makes a
second, independent owner — its own heap allocation, freed
separately, so no double-free is possible. It costs an allocation,
which is why Rust never does it silently. Correct first, fast
second: E0382's own help: even suggests this exact fix.
fn main() {
let mut v = vec![10, 20, 30];
// let first = &v[0]; // a reference INTO v
// v.push(40); // <- error[E0502]: may reallocate,
// // first would dangle
// println!("{first}");
// The safe shape: finish reading, THEN mutate.
let first = v[0]; // copy the i32 out (i32 is Copy)
v.push(40);
println!("first was {first}, v is now {v:?}");
}
Uncomment the first block and rustc raises E0502 — a shared borrow
of v can't coexist with a mutation that might reallocate its
buffer. The safe version copies the i32 out (integers are Copy),
ending the borrow before push. Prints first was 10, v is now
[10, 20, 30, 40].
Check the concept
One question at a time. Unsure? Revisit the lecture, then answer.
The challenge
Pass the quiz to unlock the challenge — your code will still be waiting here.