Search code examples
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.

  • So n is None
  • Therefore I would expect, that in the second line just None is assigned to m.
  • But when running the code I get a panic, because it's tried to unwrap n which is None. Of course this panics, but why is n.unwrap() executed, if n is None? I would have assumed, that the expression of and() is only evaluated, if the option is not None, which is obviously not the case. What have I missed?

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.