Rust Function: Process result handling
Rust Pattern Maching: Exercise-9 with Solution
Write a Rust function that takes a Result
Sample Solution:
Rust Code:
// Function that processes a Result<i32, &str> and returns either the integer if it's Ok(i32)
// or the uppercase version of the string if it's Err(&str).
fn process_result(result: Result<i32, &str>) -> String {
// Use a match expression to handle both Ok and Err variants of the Result
match result {
// If the Result is Ok(i32), return the integer
Ok(num) => num.to_string(),
// If the Result is Err(&str), convert the string to uppercase and return it
Err(s) => s.to_uppercase(),
}
}
fn main() {
// Example usage
let ok_result: Result<i32, &str> = Ok(200);
let err_result: Result<i32, &str> = Err("error message!");
println!("{}", process_result(ok_result)); // Output: 42
println!("{}", process_result(err_result)); // Output: ERROR MESSAGE
}
Output:
200 ERROR MESSAGE!
Explanation:
In the exercise above,
- The "process_result()" function takes a Result<i32, &str> as input and returns a String.
- Inside the function, a 'match' expression is used to handle both the 'Ok' and 'Err' variants of the 'Result'.
- If the 'Result' is 'Ok(i32)', the function converts the integer to a string using "to_string()" and returns it.
- If the 'Result' is 'Err(&str)', the function converts the string to uppercase using to_uppercase() and returns it.
- In the "main()" function, example 'Result' values are created and passed to "process_result()", and the result of each call is printed.
Rust Code Editor:
Previous: Rust Function: Check character case.
Next: Rust Function: Process Tuples handling.
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://www.w3resource.com/rust/functional-programming/rust-pattern-matching-exercise-9.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics