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

后端 未结 2 1503
情深已故
情深已故 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:17

    According to the Rust Book (emphasis mine):

    The value of the expression is the value of the last expression in whichever branch was chosen. An if without an else always results in () as the value.

    This gives a constraint on the expression value inside the curly braces.

    This is correct since the expression type matches ():

    if let Some(_) = some() {
        ()
    };
    

    This is correct since there's an else statement (and the types between the branches match):

    if let Some(_) = some() {
        true
    } else {
        false
    };
    

    But this is wrong:

    if let Some(_) = some() {
        true
    };
    

    This answer was inspired by this comment.

提交回复
热议问题