问题
The return type of a block is inferred.
fn main() {
let x = { 5 };
println!("{}", x);
}
But when I give the block a name, I have to specify a type.
fn five() -> i32 {
5
}
fn main() {
let x = five();
println!("{}", x);
}
How can I avoid selecting a type?
回答1:
You cannot. Rust explicitly prohibits this by design.
However, for large and complex return types, you have the following options:
- Use a closure instead - As it is local, it is allowed to infer its type
- Return a boxed type
- Return an abstract type
You can see a practical example of these in the answer for What is the correct way to return an Iterator (or any other trait)?
来源:https://stackoverflow.com/questions/47347962/how-to-infer-the-return-type-of-a-function