If let match error [SOLVED]

I have been trying these codes for days and it's not working.

What's the error?

fn main() {
    if let Some(3) = some_u8_value {
        // Error: cannot find value `some_u8_value` in the scope
        // not found in the scope
        println!("three");
    }
}

The error message cannot find value `some_u8_value` in this scope is trying to say that some_u8_value is the name of a variable but the compiler could not figure out where that variable is defined. In your example, some_u8_value is actually not defined at all. To solve that problem you could, for example, define it using a let-statement.

fn main() {
    let some_u8_value = Some(3_u8);
    if let Some(3) = some_u8_value {
        println!("three");
    }
}

It is usually a bad practice to use if let expressions when the left-hand-side pattern doesn’t bind anything. better alternatives would be:

fn main() {
    let some_u8_value = Some(3_u8);
    if some_u8_value == Some(3) {
        println!("three");
    }
}

or

fn main() {
    let some_u8_value = Some(3_u8);
    if matches!(some_u8_value, Some(3)) {
        println!("three");
    }
}
1 Like