Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ….

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading