8.14 Type Inference for Function Return Types
Rust’s type inference applies chiefly to local variables. Typically, you must specify a function’s return type explicitly:
#![allow(unused)] fn main() { fn add(a: i32, b: i32) -> i32 { a + b } }
8.14.1 impl Trait
Syntax
When returning more complex or anonymous types (like closures), you can use impl Trait
to let the compiler infer the exact type:
#![allow(unused)] fn main() { fn make_adder(x: i32) -> impl Fn(i32) -> i32 { move |y| x + y } }
This returns “some closure that implements Fn(i32) -> i32
,” without forcing you to name the closure’s type.