简体   繁体   English

为什么 Rust 不推断此闭包的返回类型?

[英]Why does Rust not infer this closure's return type?

The Rust compiler is usually able to infer the type of an expression that is returned from a closure: Rust 编译器通常能够推断从闭包返回的表达式的类型:

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 :但是当我使用return语句定义相同的闭包时,编译器无法推断类型:

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?我很惊讶 Rust 不能在这里推断类型:是否可以在闭包中使用return语句而不阻止编译器推断其返回类型?

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 .如果没有分号,则返回最后一个表达式,最后一个表达式是return num + 1.0 Since a return statement makes the program jump somewhere, else, it's value can be anything, for example:由于 return 语句使程序跳转到某个地方,否则它的值可以是任何值,例如:

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.但是,如果编译器没有看到直接分配给它的类型,它将选择 type ()作为 return 语句的值。

So what happened is:所以发生的事情是:

  1. The compiler sees the last expression in the closure, and assigns it the type () by default.编译器看到闭包中的最后一个表达式,并默认为其分配类型()
  2. The compiler then sees an explicit return inside the closure, which returns the type i32 .然后编译器在闭包内看到一个显式返回,它返回类型i32

So since there are two attempts to return from the closure, and they each return different types, that's a type mismatch.因此,由于有两次尝试从闭包返回,并且它们各自返回不同的类型,所以这是类型不匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM