Why does the compiler assume that the value of if let should be `()`?

后端 未结 2 1522
情深已故
情深已故 2021-01-21 15:52

I have the following code:

use std::collections::HashSet;

fn translate() -> Option {
    None
}

fn main() {
    let mut found = HashSet::new()         


        
2条回答
  •  無奈伤痛
    2021-01-21 16:40

    When you omit a function's return type, the function actually returns (). That is,

    fn foo() {}
    

    is equivalent to:

    fn foo() -> () {}
    

    If I add return (); at the end of the function I still get the same error. So I'm not even sure if that has something to do with a function return value.

    An if let expression that is used as a statement must return (), unless it is the last expression in the function's body, in which case its type must match the function's return type. Since your if let doesn't have an else clause, its type must be ().

提交回复
热议问题