rustoption-typepanicunwrap

Why is in Rust the expression in Option.and evaluated, if option is None?


I don't understand, why Option.and() is evaluated, if option is None. The documentation says ....

Returns None if the option is None, otherwise it returns optb (the argument of and()).

So I would expect, that and() is only (and only then) taken into account, if option is not None. But obviously this is not the case. Let's look the following code ....

let n: Option<i32> = None;
let m = n.and(Some(n.unwrap()));

I know this is a stupid sample, but it's just to make hopefully my point clearer.


Solution

  • Because and() is a normal function, and when you call a function first Rust evaluates its arguments.

    What you want is and_then():

    let m = n.and_then(|_| Some(n.unwrap()));
    

    It takes a closure to be able to avoid evaluating the argument.