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() }
Checking if Option is None In this example, we use both the isDefined() method and isEmpty() to check if an optional value is None. Both methods return a Boolean value based on whether or not the value is an instance of Some or None.
Type Option represents an optional value: every Option is either Some and contains a value, or None , and does not. Option types are very common in Rust code, as they have a number of uses: Initial values. Return values for functions that are not defined over their entire input range (partial functions)
The Option<T> enum has two variants: None , to indicate failure or lack of value, and. Some(value) , a tuple struct that wraps a value with type T .
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() { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With