Skip to content
Related Articles
Open in App
Not now

Related Articles

Rust – Unpacking Options Using “?” Operator

Improve Article
Save Article
  • Last Updated : 15 Sep, 2022
Improve Article
Save Article

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 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;



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 program Unpacking Options with "?"
fn main()
fn func_name (choice: Option<u8>) -> Option<String> {
    let next_choice: u8 = choice ? + 1;
    Some(format!("Lets buy {} courses", next_choice))



My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!