Open In App

Rust – Unpacking Options Using “?” Operator

Improve
Improve
Like Article
Like
Save
Share
Report

In Rust, there is a concept of the match and some.

  • Match refers to a condition where an enum (type T) is found
  • None refers to the condition when no element is found.

The match statement is responsible for the explicit handling of this situation and unwraps statement is used for implicit handling. Implicit handling returns panic or an inner element.

Example 1:

Rust




// Rust code for "?" operator
fn func_name(choice: Option<&str>) {
    match choice {
        Some("dsa")   => println!("lets practice DSA"),
        Some(gfg)   => println!("Lets buy {} courses", gfg),
        None          => println!("Lets learn Rust from GFG"),
    }
}
  
fn main() {
    let dsa  = Some("dsa");
    let gfg = Some("gfg");
    let void  = None;
  
    func_name(dsa);
    func_name(gfg);
    func_name(void);
  }


Output:

 

Unpacking Options with “?”:

Unpack options are done by match statements but we use the “?” operator to simplify things. Considering that ‘var’ is an option then by evaluating ‘var’ ? returns a value when ‘var’ is some otherwise, nothing is returned i.e. None gets returned.

Here, if the choice is `None`, then it returns `None` and if the choice is `Some’ then it gets assigned to next_choice.

Example 2:

Rust




// Rust program Unpacking Options with "?"
#[allow(dead_code)]
fn main()
{
fn func_name (choice: Option<u8>) -> Option<String> {
      
    let next_choice: u8 = choice ? + 1;
    Some(format!("Lets buy {} courses", next_choice))
      
}}


Output:

 



Last Updated : 15 Sep, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads