Rust Function: Length of option string handling
Write a Rust function that takes an Option<&str> and returns the length of the string if it's Some(&str) and 0 if it's None.
Sample Solution:
Rust Code:
// Function that takes an Option<&str> and returns the length of the string if it's Some(&str)
// and 0 if it's None.
fn length_of_string(option_str: Option<&str>) -> usize {
// Use match to pattern match the Option
match option_str {
// If it's Some(&str), return the length of the string
Some(s) => s.len(),
// If it's None, return 0
None => 0,
}
}
fn main() {
// Example usage
let some_str = Some("Rust Exercises!"); // Option containing a string
let none_str: Option<&str> = None; // None
// Print the length of the string if it's Some(&str) or 0 if it's None
println!("{}", length_of_string(some_str)); // Output: 4
println!("{}", length_of_string(none_str)); // Output: 0
}
Output:
15 0
Explanation:
In the exercise above,
- The "length_of_string()" function takes an Option<&str> as input and returns a 'usize'.
- Inside the function, a 'match' expression is used to pattern match the 'Option'.
- If the 'Option' is 'Some(&str)', the length of the string is returned using the "len()" method.
- If the 'Option' is 'None', 0 is returned.
Rust Code Editor:
Previous: Rust Function: Process Tuples handling.
Next: Rust Function: Analyzing Boolean vector.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics