w3resource

Rust Program: Option Enum

Rust Structs and Enums: Exercise-10 with Solution

Write a Rust program that creates an enum Option with variants representing some and none states.

Sample Solution:

Rust Code:

// Define an enum named 'Option' with variants representing 'Some' and 'None' states
enum Option<T> {
    Some(T),
    None,
}

fn main() {
    // Example usage: Create variables representing 'Some' and 'None' states
    let some_value: Option<i32> = Option::Some(42);
    let none_value: Option<i32> = Option::None;

    // Print the values of the variables
    match some_value {
        Option::Some(val) => println!("Some value: {}", val),
        Option::None => println!("No value"),
    }

    match none_value {
        Option::Some(val) => println!("Some value: {}", val),
        Option::None => println!("No value"),
    }
}

Output:

Some value: 42
No value

Explanation:

Here is a brief explanation of the above Rust code:

  • We define an enum Option<T> with generic type 'T', which represents the type of value that 'Some' variant holds.
  • We define two variants: Some(T) to hold a value of type 'T', and 'None' to represent the absence of a value.
  • In the "main()" function, we create variables 'some_value' and 'none_value' representing instances of 'Option' enum with values in 'Some' and 'None' states, respectively.
  • We use pattern matching (match expressions) to print the values of these variables. If the variable is in 'Some' state, we extract and print the inner value; if it's in 'None' state, we print a message indicating the absence of a value.

Rust Code Editor:

Previous: Rust Program: Car Details.
Next: Rust Result and Option Exercises

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/rust/basic/rust-structs-and-enums-exercise-10.php