8.14 Type Inference for Function Return Types
Rust's type inference system can often determine the types of variables and expressions. However, for function signatures, return types usually need to be specified explicitly.
8.14.1 Specifying Return Types
#![allow(unused)] fn main() { fn add(a: i32, b: i32) -> i32 { a + b } }
- The return type
-> i32
is specified explicitly.
8.14.2 Omission of Return Types
In certain cases, you can use the impl Trait
syntax to allow the compiler to infer the return type, especially when returning closures or iterators.
#![allow(unused)] fn main() { fn make_adder(x: i32) -> impl Fn(i32) -> i32 { move |y| x + y } }
- Here,
impl Fn(i32) -> i32
tells the compiler that the function returns some type that implements theFn(i32) -> i32
trait.
Note: For regular functions returning concrete types, you must specify the return type.