Rust Function: String length
Rust Result and Option types: Exercise-6 with Solution
Write a Rust function that takes a string and returns Option
Sample Solution:
Rust Code:
fn string_length(string: &str) -> Option<usize> {
// Check if the input string is empty
if string.is_empty() {
// If the string is empty, return None
None
} else {
// If the string is not empty, return Some with the length of the string
Some(string.len())
}
}
fn main() {
// Test cases
let empty_string = "";
let non_empty_string = "Rust, world!";
// Test the string_length function with an empty string
match string_length(empty_string) {
Some(length) => println!("Length of '{}' is {}", empty_string, length),
None => println!("Empty string provided"),
}
// Test the string_length function with a non-empty string
match string_length(non_empty_string) {
Some(length) => println!("Length of '{}' is {}", non_empty_string, length),
None => println!("Empty string provided"),
}
}
Output:
Empty string provided Length of 'Rust, world!' is 12
Explanation:
Here's a brief explanation of the above Rust code:
The function "string_length()" takes a string 'string' as input and returns an Option
Rust Code Editor:
Previous: Rust Function: Date string parsing.
Next: Rust Function: Hex string to integer.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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/error_handling/rust-result-and-option-types-exercise-6.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics