Sub topic 16
Common pitfalls and compiler errors
This chapter collects the mistakes that most often trip up intermediate Rust programmers working with closures and iterators. For each one it shows the symptom, the cause, and the fix. It assumes you know ownership and borrowing, generic trait bounds, Option and Result, and the closure and iterator material from the earlier chapters.
Reading the error first
Most closure and iterator errors fall into three groups: ownership (who owns a captured value), borrowing (who holds a reference and for how long), and types (what the iterator yields). The diagram gives a quick way to sort an error into one of them.
Pitfall 1: the pipeline that never runs
Adapters such as map are lazy. If nothing consumes the iterator, the closure never runs. The compiler warns with unused ... that must be used, but it is only a warning, so the program still builds and does nothing.
fn main() {
let v = vec![1, 2, 3];
// Warning: does nothing, because no consumer drives the iterator.
v.iter().map(|x| println!("saw {}", x));
// Use a consumer such as for_each when you want side effects.
v.iter().for_each(|x| println!("saw {}", x));
}Prefer for_each or a plain for loop for side effects. Keep map for transformations that produce values.
Pitfall 2: a closure that outlives what it borrows
By default a closure borrows what it captures. If you return it, or send it to another thread, the borrowed variable may be gone by the time the closure runs. The compiler reports E0373: closure may outlive the current function, but it borrows ... and suggests move.
fn make_adder(n: i32) -> impl Fn(i32) -> i32 {
move |x| x + n
}
fn main() {
let add10 = make_adder(10);
println!("{}", add10(5)); // 15
}Without move, the closure would hold a reference to the parameter n, which is dropped when make_adder returns. The same error appears with thread::spawn.
Pitfall 3: a bound stricter than the closure body
The three closure traits form a hierarchy. A closure that mutates captured state is FnMut, and a closure that moves a captured value out is FnOnce. If a function asks for a stricter trait than the closure body allows, you get one of these errors:
| Error | Meaning | Usual fix |
|---|---|---|
| `E0525` expected a closure that implements `Fn`, but this closure only implements `FnOnce` | The body moves a captured value out | Clone inside the closure, or loosen the bound to `FnOnce` |
| `E0594` / `E0596` cannot assign to or borrow captured variable in an `Fn` closure | The body mutates a capture, but the bound says `Fn` | Change the bound to `FnMut` |
| `E0382` use of moved value: closure cannot be invoked more than once | A closure that is only `FnOnce` was called twice | Call it once, or make it `Fn` or `FnMut` |
Here is the clone fix for a closure that would otherwise be FnOnce:
fn call_twice<F: Fn() -> String>(f: F) -> (String, String) {
(f(), f())
}
fn main() {
let name = String::from("ferris");
// `move || name` would hand `name` out on the first call (FnOnce).
// Cloning inside keeps ownership in the closure, so it is Fn.
let get = move || name.clone();
println!("{:?}", call_twice(get));
}When you write your own functions, choose the loosest bound that works. Use FnOnce if you call the closure once, FnMut if you call it repeatedly and it may mutate state, and Fn only when you need shared or concurrent calls.
Pitfall 4: using a variable while a closure borrows it
A mutating closure holds a mutable borrow for as long as the closure is still used later. Touching the variable in between gives E0502 (mutable and immutable borrow) or E0499 (two mutable borrows).
fn main() {
let mut log: Vec<String> = Vec::new();
let mut record = |s: &str| log.push(s.to_string());
record("a");
record("b");
// The last use of `record` is above, so the mutable borrow has ended.
println!("{:?}", log); // ["a", "b"]
}If you moved the println! above the second record("b") call, the program would not compile. The closure would still be in use after the shared borrow. Borrows end at the last use, not at the end of the scope, so reordering statements is often the whole fix.
Pitfall 5: counting reference levels
iter() yields &T. Adapters like filter pass their closure a reference to the item, so on iter() the closure sees &&T. Comparing &&i32 to an i32 gives a mismatched types or cannot apply operator error, and collecting &i32 items into Vec<i32> fails with a value of type Vec<i32> cannot be built from an iterator over elements of type &i32.
fn main() {
let nums = vec![1, 2, 3, 4, 5, 6];
// Option A: destructure the references in the closure parameter.
let a: Vec<i32> = nums.iter().filter(|&&n| n % 2 == 0).cloned().collect();
// Option B: copy the items first, so the closure sees &i32.
let b: Vec<i32> = nums.iter().copied().filter(|n| *n % 2 == 0).collect();
println!("{:?} {:?}", a, b); // [2, 4, 6] [2, 4, 6]
}copied() works for Copy types and cloned() for Clone types. For types that are expensive to clone, keep the references and collect into Vec<&T> instead.
Pitfall 6: `into_iter` consumes the collection
For a Vec<T> that you own, into_iter() moves the vector, and later use gives E0382: borrow of moved value. A for loop over names does the same thing. When you still need the original, iterate over names.iter() or &names.
fn main() {
let names = vec![String::from("ada"), String::from("grace")];
let upper: Vec<String> = names.iter().map(|s| s.to_uppercase()).collect();
println!("{:?} {:?}", names, upper); // both still usable
}Pitfall 7: type annotations needed
collect, sum, product and parse can each produce many types, so the compiler needs to know which one you want. Without that, you get E0282 or E0283: type annotations needed. Supply the type with a binding annotation or with the turbofish (::<T>).
fn main() {
let squares = (1..=3).map(|n| n * n).collect::<Vec<u32>>();
let total = squares.iter().sum::<u32>();
println!("{:?} {}", squares, total); // [1, 4, 9] 14
}Pitfall 8: two closures, two types
Every closure has its own anonymous type, even if two closures have identical signatures. An if that returns a different closure in each branch fails with E0308: mismatched types, and impl Fn does not help, because it still stands for one concrete type. Box both branches as trait objects:
fn pick(double: bool) -> Box<dyn Fn(i32) -> i32> {
if double {
Box::new(|x| x * 2)
} else {
Box::new(|x| x + 1)
}
}
fn main() {
println!("{} {}", pick(true)(5), pick(false)(5)); // 10 6
}The cost is one heap allocation and a dynamic call, which is acceptable here.
Pitfall 9: reusing an iterator that a consumer took
Methods like take, sum and collect take self by value, so they consume the iterator. Using it afterwards gives E0382. To use part of an iterator and keep the rest, borrow it with by_ref():
fn main() {
let mut it = 1..=10;
let first: Vec<i32> = it.by_ref().take(3).collect();
let rest: i32 = it.sum();
println!("{:?} {}", first, rest); // [1, 2, 3] 49
}A short checklist
- Read the first error only. Later errors are often side effects of it.
- If the message says "may outlive", add
move. - If it says "only implements FnOnce", look for a captured value being moved out of the body.
- If it says "type annotations needed", annotate the
collectorsumtarget. - If an item type does not match, work out how many
&the iterator yields at that point.
Exercise
This function fails to compile with E0373 ("closure may outlive the current function, but it borrows prefix"). What is the smallest change that fixes it, and why does it work? The function is fn labeler(prefix: String) -> impl Fn(&str) -> String { |s| format!("{}{}", prefix, s) }.
Show answer
Add move before the closure: move |s| format!("{}{}", prefix, s). Without it, the closure borrows prefix, which is dropped when labeler returns. With move, the closure takes ownership of prefix, so it can live as long as the caller needs. The closure only reads prefix, so it still implements Fn.
Exercise
let evens: Vec<i32> = nums.iter().filter(|n| n % 2 == 0).collect(); has two separate problems when nums is a Vec<i32>. Name both and give a corrected version.
Show answer
First, inside filter the parameter n has type &&i32, so n % 2 is not defined. Second, iter() yields &i32, so collect cannot build a Vec<i32> from it. One fix is nums.iter().copied().filter(|n| *n % 2 == 0).collect(). Another is nums.iter().filter(|&&n| n % 2 == 0).cloned().collect().