Sub topic 1
Closure syntax: anonymous functions that remember things
A closure is an anonymous function that can use variables from the scope where it was written. You can store it in a variable, pass it to another function, and call it later. This chapter covers the syntax, how the compiler infers types, and how closures differ from ordinary fn items. The following chapters cover capture modes, the Fn traits, and iterators.
Prerequisites
This chapter assumes you know:
- Rust basics: variables, functions, structs and enums.
- Ownership, borrowing and references.
- Basic generics and trait bounds.
OptionandResult.- How to use
Vecand slices.
You don't need any knowledge of iterators yet. A few examples call standard library methods that take closures, and each one is explained where it appears.
The basic shape
A closure starts with a pair of vertical bars that hold the parameters. The body follows the bars.
fn add_one_v1(x: i32) -> i32 { x + 1 }
fn main() {
let add_one_v2 = |x: i32| -> i32 { x + 1 };
let add_one_v3 = |x| x + 1;
let add_one_v4 = |x| { x + 1 };
println!("{}", add_one_v1(1)); // 2
println!("{}", add_one_v2(1)); // 2
println!("{}", add_one_v3(1)); // 2
println!("{}", add_one_v4(1)); // 2
}The four definitions do the same work, and each drops more annotation than the one before.
add_one_v1is a normal function item. It needs full type annotations.add_one_v2is a closure with every annotation spelled out. Once you write a return type with->, the body must be a block in braces.add_one_v3has no annotations and a single-expression body, so no braces are needed.add_one_v4has braces but no annotations. The braces are optional for a single expression.
A closure that takes no arguments uses empty bars, ||:
fn main() {
let greet = || println!("hello");
greet();
greet();
}When the body needs several statements, use a block. The last expression, without a semicolon, is the value of the closure:
fn main() {
let describe = |n: i32| {
let label = if n % 2 == 0 { "even" } else { "odd" };
format!("{} is {}", n, label)
};
println!("{}", describe(7)); // 7 is odd
}Type inference and its limit
A function item is part of a public interface, so Rust requires you to annotate its signature. A closure usually lives in a small local scope, so the compiler infers its parameter and return types from how you use it.
The inference has one rule that surprises people. The compiler fixes each type from the first use, and the closure keeps those types for the rest of its life.
fn main() {
let echo = |x| x;
let a = echo(5);
println!("{}", a);
// let b = echo(String::from("hi")); // error[E0308]: mismatched types
}If you uncomment the last line, the compiler rejects it. The call echo(5) made x an integer, and a String no longer fits. A generic function would accept both types. A closure is not generic.
Inference also needs something to work from. If you define |x| x + 1 and never call it, the compiler can't tell what x is and reports error E0282 ("type annotations needed"). Add a type to the parameter, or call the closure.
Remembering the environment
The feature that sets closures apart from fn items is access to the surrounding scope.
fn main() {
let factor = 3;
let scale = |x: i32| x * factor;
println!("{}", scale(4)); // 12
}The body of scale uses factor, which is defined outside the closure. We say the closure captures factor. Doing the same with a nested fn fails:
fn main() {
let factor = 3;
// fn scale(x: i32) -> i32 { x * factor }
// error[E0434]: can't capture dynamic environment in a fn item
println!("{}", factor);
}A fn item is just code with a name. It can't see local variables, even when it is declared inside another function. A closure is code plus the values it captured.
How the capture happens (a shared borrow, a mutable borrow, or a move) depends on what the body does with the variable. The next chapter covers that. For now, note that scale only reads factor, so it borrows it.
Closures compared with fn items
| Property | `fn` item | Closure |
|---|---|---|
| Needs a name | Yes | No, but you can bind it to a variable |
| Parameter and return types | Must be annotated | Usually inferred |
| Can use local variables | No | Yes |
| Type | A named function type | A unique anonymous type |
| Call syntax | `f(x)` | `f(x)` |
The call syntax is identical, so a caller can't tell which one it has by looking at the call.
Every closure has its own type
The compiler creates a new, unnamed type for each closure expression. Two closures with identical bodies still have different types. You can't write that type in an annotation. You refer to it through trait bounds such as Fn(i32) -> i32, which the later chapters on Fn traits and function parameters cover.
There is one convenient exception. A closure that captures nothing can be converted to a plain function pointer, written fn(i32) -> i32:
fn apply(f: fn(i32) -> i32, x: i32) -> i32 {
f(x)
}
fn double(x: i32) -> i32 {
x * 2
}
fn main() {
let inc: fn(i32) -> i32 = |x| x + 1;
println!("{}", apply(inc, 1)); // 2
println!("{}", apply(double, 4)); // 8
println!("{}", apply(|x| x - 1, 10)); // 9
}The conversion works for non-capturing closures only. If the closure uses factor from the earlier example, it can't become a fn pointer, because a bare function pointer has nowhere to store the captured value. Code written against fn(i32) -> i32 is therefore less flexible than code written against a closure bound. It accepts ordinary functions and non-capturing closures, but nothing that captures.
Closures in everyday standard library calls
Many standard library methods take a closure. Two you can try now:
fn main() {
let maybe = Some(3);
let doubled = maybe.map(|n| n * 2);
println!("{:?}", doubled); // Some(6)
let mut names = vec!["christopher", "bob", "alice"];
names.sort_by_key(|name| name.len());
println!("{:?}", names); // ["bob", "alice", "christopher"]
}Option::map applies the closure to the value inside Some and leaves None alone. sort_by_key calls the closure on each element to get a sort key, here the string length. In both cases the compiler infers the type of the closure parameter from the method's signature, so you need no annotation. This is the most common reason closures go unannotated.
Common syntax mistakes
- Missing braces after
->.|x: i32| -> i32 x + 1is a syntax error. With an explicit return type, wrap the body in{ }. - Trailing semicolon in the body.
|x: i32| -> i32 { x + 1; }makes the block evaluate to(), which doesn't matchi32. Remove the semicolon. - Confusing
|with||. Empty bars,||, mean "no parameters". In a position where an expression is expected, they are not a logical OR. - Mixing types across calls. As shown above, the first call decides the types.
- Forgetting
muton the binding. Calling some closures requireslet mut, because calling them changes captured state. The next chapter explains this.
Exercise
This code fails to compile. Which line causes the error, and why? let double = |x| x * 2; let a = double(2); let b = double(2.5);
Show answer
The last line fails. The first call, double(2), fixes the parameter type as an integer. The call double(2.5) passes a floating-point number and produces a mismatched types error (E0308). The fix is to write two closures, or to annotate x as f64 and call double(2.0).
Exercise
Write a closure named with_tax that takes a price of type f64 and returns the price plus a tax computed from a local variable rate defined before the closure. Call it with 100.0 when rate is 0.2 and say what it prints.
Show answer
let rate = 0.2; let withtax = |price: f64| price * (1.0 + rate); println!("{}", withtax(100.0)); This prints 120 (the exact float result may print as 120). The closure captures rate by shared borrow, because it only reads it. A nested fn could not do this.