The Rust compiler is usually able to infer the type of an expression that is returned from a closure:
fn main() {
let a_closure = |num|{
num+1.0
};
println!("{}", a_closure(1.0));
}
But the compiler is unable to infer the type when I define the same closure using a return
statement :
fn main() {
let a_closure = |num|{
return num+1.0
};
println!("{}", a_closure(1.0));
}
/*
error[E0308]: mismatched types
--> src/main.rs:3:9
|
3 | return num+1.0
| ^^^^^^^^^^^^^^ expected `()`, found `f64`
*/
I'm surprised that Rust can't infer the type here: is it possible to use a return
statement in a closure without preventing the compiler from inferring its return type?
This is due to the lack of a semicolon. When you have no semicolon, the last expression is returned, and this last expression is return num + 1.0
. Since a return statement makes the program jump somewhere, else, it's value can be anything, for example:
fn main() {
let a: String = return;
}
However, if the compiler sees no direct type assigned to it, it will pick the type ()
as the value of the return statement.
So what happened is:
()
by default.i32
.So since there are two attempts to return from the closure, and they each return different types, that's a type mismatch.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.