How do I conditionally execute code only when an Option is None?

Viewed 36724

I don't want to take action if the function returns a value in the optional; how do I test the None case only? This code works, but it looks horrible.

let v = ffunc();
match v {
  None => { callproc() }, 
  Some(x) => {  }
}

In C, I can write:

int x = ffunc();
if ( !x ) { callproc() } 
4 Answers

To check if an Option is None you can either use Option::is_none or use the if let syntax.

For example:

let x = ffunc();

if let None = x {
    println!("x is None")
}

Or using the Option::is_none function:

let x = ffunc();

if x.is_none() {
    println!("x is None")
}

If you are not interested in the value, just use

if v.is_none() { ... }

To complete the answer above, if the option is Some(x):

let v = ffunc()
if let Some(x) = v {
    func_to_use_x(x);
} else {
    callproc();
}

If you don't care about the value in the option, then:

if v.is_none() {...}

or

if v.is_some() {...}

If you want to insert a value into the Option if it's None, and get the value otherwise, you can use get_or_insert

let mut x = None;
let y = x.get_or_insert(5);

assert_eq!(y, &5);
assert_eq!(x, Some(5));

Or get_or_insert_with for lazily evaluation:

let mut x = None;
let y = x.get_or_insert_with(|| 5);

assert_eq!(y, &5);
assert_eq!(x, Some(5));

You can also use or and or_else to return a new Option, instead of mutating the original:

let x = None;
assert_eq!(x.or(Some(100)), Some(100));

let x = None;
assert_eq!(x.or_else(|| Some(100)), Some(100));
Related