If let statements

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

In this we are assigning some_u8_value to Some(0u8). Does this mean that are assigning Option<u8> data type to some_u8_value?

And in the if let statement, if let Some(3) = some_u8_value, what are we really trying to do over here? I am a bit confused.

Yes. If you want to check a variable's type, try to assign it the wrong type. The compiler will tell what it is, for example:

let some_u8_value: () = Some(0u8);

expected type `()`
found type `std::option::Option<u8>`

if let is useful when you would use a match but only care about a single arm (or case). Your if let is equivalent to:

match some_u8_value {
    Some(3) => println!("three"),
    _ => {},
}

We only care about the case where we have a Some and this Some is equal to 3.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.