Sub topic 1
Closure syntax: anonymous functions that remember things
Prerequisites
This chapter assumes you know the following:
- Rust basics: variables, functions, structs and enums.
- Ownership and references, at the level of "a value has one owner and can be borrowed."
- Basic generics and trait bounds.
You don't need to know iterators yet. Later chapters build on this one.
What a closure is
A closure is an anonymous function that you can store in a variable or pass to another function. Unlike a plain fn item, a closure can use variables from the scope where it was written. The compiler records which variables it uses. That is the "remembers things" part.
fn main() {
let factor = 3;
let scale = |x: i32| x * factor;
println!("{}", scale(4)); // 12
}The parameters go between | bars. The body follows. The closure scale reads factor, which is defined outside it. A nested fn could not do this, because fn items do not see local variables of the enclosing function.
Syntax variations
Closures can be written with more or less detail. These four definitions are equivalent:
fn main() {
fn add_one_fn(x: i32) -> i32 { x + 1 }
let add_one_full = |x: i32| -> i32 { x + 1 };
let add_one_short = |x: i32| x + 1;
let add_one_inferred = |x| x + 1;
println!("{}", add_one_fn(1));
println!("{}", add_one_full(1));
println!("{}", add_one_short(1));
println!("{}", add_one_inferred(1));
}The rules are:
- Parameter and return types are optional. The compiler infers them from the body and the first use.
- If you write a return type, the body must be a block in braces.
- A single expression needs no braces.
- A closure with no parameters uses empty bars:
|| 42.
Types are fixed after the first call
Inference picks one concrete type per parameter. It does not make the closure generic.
fn main() {
let echo = |x| x;
let a = echo(String::from("hi"));
println!("{}", a);
// let b = echo(5); // error[E0308]: mismatched types
}The first call fixes x as String. Calling echo(5) afterward fails to compile. If you need a function that works for many types, use a generic fn.
Each closure has its own type
Every closure expression gets a unique, unnamed type generated by the compiler. Two closures with identical bodies still have different types. This is why you will later use trait bounds such as Fn(i32) -> i32 to accept closures, and why returning one needs impl Fn or Box<dyn Fn>. Those topics come in later chapters.
Common errors
| Mistake | Result | Column | Column |
|---|---|---|---|
| Calling the same inferred closure with two different types | `mismatched types` error at the second call | ||
| Giving a return type but no braces: `\ | x\ | -> i32 x + 1` | Syntax error. Add `{ }` around the body |
| Using a local variable inside a nested `fn` | `can't capture dynamic environment in a fn item` | ||
| Never calling the closure | No error, but the body never runs |
Exercises
Exercise
Why does this code fail to compile? let f = |x| x + 1; f(1u8); f(1.5f64);
Show answer
The compiler infers one concrete type for the parameter x from the first call, u8. The second call passes an f64, which is a different type, so it produces a mismatched types error. A closure is not generic. Use a generic function if you need several types.
Exercise
Rewrite fn double(x: i32) -> i32 { x * 2 } as a closure with no type annotations, and name one thing a closure can do that this fn cannot.
Show answer
let double = |x| x * 2;. A closure can use variables from the scope where it is defined, such as let factor = 3; let scale = |x| x * factor;. A fn item cannot.