Type inference and return statements

The Rust compiler sometimes can't infer a closure's return type if I use a return statement. Is this a bug?

Not seen any similar posting before. I expect your rare wanting to put return in closure.

Wondered if regression; but errors on 1.0.0

<source>:3:16: 3:23 error: type mismatch resolving `<f64 as core::ops::Add>::Output == ()`:
 expected f64,
    found () [E0271]
<source>:3         return num+1.0
                              ^~~~~~~
<source>:5:20: 5:34 error: the trait `core::fmt::Display` is not implemented for the type `()` [E0277]
<source>:5     println!("{}", a_closure(1.0));
                                  ^~~~~~~~~~~~~~
note: in expansion of format_args!
<std macros>:2:25: 2:56 note: expansion site
<std macros>:1:1: 2:62 note: in expansion of print!
<std macros>:3:1: 3:54 note: expansion site
<std macros>:1:1: 3:58 note: in expansion of println!
<source>:5:5: 5:36 note: expansion site
<source>:5:20: 5:34 note: `()` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string
<source>:5     println!("{}", a_closure(1.0));
                                  ^~~~~~~~~~~~~~
note: in expansion of format_args!
<std macros>:2:25: 2:56 note: expansion site
<std macros>:1:1: 2:62 note: in expansion of print!
<std macros>:3:1: 3:54 note: expansion site
<std macros>:1:1: 3:58 note: in expansion of println!
<source>:5:5: 5:36 note: expansion site
error: aborting due to 2 previous errors
Compiler returned: 101

My guess is that the return results in needing to know the return type earlier in the compilation process, and there's nothing in the context of your assignment of the closure to a variable to suggest any particular return type, so it falls back to ().

E.g. this works:

fn main() {
    let a_closure: fn(f32) -> f32 = |num|{
        return num+1.0
    };
    println!("{}", a_closure(1.0));
}

As does this:

fn main() {
    let num = Some(1.0);
    let inc = num.map(|num| return num + 1.0);
    println!("{:?}", inc);
}
1 Like