If you attempt to define a closure without concrete types, Rust will infer the types the first time the closure is called. In the following example, Rust will infer that the type of x
in |x| x + 1
is an i32
, and, if you attempt to use this closure with any other type, it will fail to compile.
fn main() {
let add_one = |x| x + 1;
let x = 5;
println!("{} + 1 = {}", x, add_one(x));
let y = 10.0;
println!("{} + 1 = {}", y, add_one(y));
}
The second call to add_one
fails because the type i32
has been locked into the closure.