Sub topic 16
Common pitfalls and compiler errors
This chapter assumes you know closure capture modes, the Fn, FnMut and FnOnce traits, and the basic iterator adapters and consumers. Most closure and iterator errors come from a few causes. Once you can recognize them, the compiler's messages become easy to act on.
Pitfall 1: Calling a closure that consumes its capture twice
A closure that moves a captured value out of itself, for example by returning it, implements only FnOnce. The compiler reports "use of moved value" (E0382) on the second call. The usual fix is to clone instead of moving out.
fn main() {
let name = String::from("Ada");
let get = || name.clone();
println!("{} {}", get(), get());
}Because clone only borrows name, the closure is Fn and can be called any number of times.
Pitfall 2: Using a variable while a closure borrows it mutably
A closure that mutates a capture holds a mutable borrow for as long as the closure is still used later. Reading the variable in between triggers E0502 or E0499.
fn main() {
let mut count = 0;
let mut inc = || count += 1;
inc();
inc();
println!("{}", count);
}This compiles because inc is not used after the println!, so its borrow has ended. Move that last call after the println! and the error returns.
Pitfall 3: Spawning a thread without move
A spawned thread may outlive the function that created it. A closure that only borrows local data is rejected with E0373 ("closure may outlive the current function"). Add move so the closure owns its data, as in the thread example earlier in this tutorial.
Pitfall 4: Double references in filter
iter() yields &T, and filter passes its closure a reference to each item. The closure parameter is therefore &&T.
fn main() {
let nums = vec![1, 2, 3, 4];
let evens: Vec<&i32> = nums.iter().filter(|x| **x % 2 == 0).collect();
println!("{:?}", evens);
}Dereference twice, or destructure the parameter with a pattern such as |&&x|. Use .copied() or .cloned() if you want owned values in the result.
Pitfall 5: Missing type for collect
collect can build many collection types, so the compiler cannot guess which one you want. Without a target type you get E0282 or E0283 ("type annotations needed"). Name the type on the variable or use the turbofish.
fn main() {
let words = ["a", "bb", "ccc"];
let lens = words.iter().map(|w| w.len()).collect::<Vec<_>>();
println!("{:?}", lens);
}The _ lets the compiler infer the element type.
Pitfall 6: Building a pipeline and never consuming it
Adapters are lazy. A chain that ends in map or filter does nothing, and the compiler warns "unused Map that must be used". End the chain with a consumer such as collect, sum or for_each. Use a plain for loop when the goal is only side effects.
Pitfall 7: Using a collection after into_iter
into_iter() on a Vec takes ownership. Using the vector afterwards gives "borrow of moved value". Call iter() when you only need to read.
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| E0382 on a second closure call | Closure is `FnOnce` | Clone, or call only once |
| E0502 or E0499 near a closure | Live mutable borrow | End closure use first |
| E0373 with `thread::spawn` | Closure borrows locals | Add `move` |
| Type mismatch `&&i32` vs `i32` | `filter` adds a reference | Dereference or `copied()` |
| E0282 or E0283 on `collect` | No target type | Annotate or use turbofish |
| Warning: unused `Map` | No consumer | Add `collect`, `sum`, and so on |
Exercise
The line let total = v.iter().map(|x| x * 2); compiles with a warning, and total is never a number. What is wrong, and how do you fix it?
Show answer
map is lazy and no consumer drives the iterator, so no values are computed. Add a consumer and a type, for example let total: i32 = v.iter().map(|x| x * 2).sum();.