w3resource

Rust Function: Print optional integer

Rust Basic: Exercise-17 with Solution

Write a Rust function that takes an optional integer and prints its value if it exists.

Sample Solution:

Rust Code:

// Define a function named 'print_optional_integer' that takes an optional integer 'num' as input
fn print_optional_integer(num: Option) {
    // Match on the 'num' parameter to handle both Some and None cases
    match num {
        // If 'num' contains a value, print it
        Some(value) => println!("The value is: {}", value),
        // If 'num' is None, print a message indicating absence of value
        None => println!("The value is absent"),
    }
}

fn main() {
    // Call the 'print_optional_integer' function with Some and None values
    print_optional_integer(Some(42)); // Prints: The value is: 42
    print_optional_integer(None);     // Prints: The value is absent
}

Output:

The value is: 42
The value is absent

Explanation:

Here's a brief explanation of the above Rust code:

  • fn print_optional_integer(num: Option<i32>) { ... }: This function is defined to take an Option<i32> as input, representing an optional integer.
  • match num { ... }: This is a match expression that matches on the 'num' parameter to handle both 'Some' and 'None' cases.
  • Some(value) => println!("The value is: {}", value),: This arm of the match expression is executed if 'num' contains a value ('Some'). It extracts the value from 'Some' and prints it.
  • None => println!("The value is absent"),: This arm is executed if 'num' is 'None'. It prints a message indicating the absence of a value.
  • fn main() { ... }: This is the entry point of the program. It calls the "print_optional_integer()" function with both 'Some' and 'None' values to demonstrate its functionality.

Rust Code Editor:

Previous: Rust Enum: Define Colors.
Next: Rust Function: Check Positive numbers.

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://w3resource.com/rust/basic/rust-basic-exercise-17.php