Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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() }  
like image 791
Mens Rifles Avatar asked Nov 06 '18 18:11

Mens Rifles


People also ask

How do you know if an option is in none?

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.

What is Option <> in Rust?

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)

What is some and none in Rust?

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 .


2 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") } 
like image 103
belst Avatar answered Sep 17 '22 17:09

belst


If you are not interested in the value, just use

if v.is_none() { ... } 
like image 23
user2722968 Avatar answered Sep 16 '22 17:09

user2722968