w3resource

Rust Result and Option Exercises with Solutions and Explanations

Rust Result and Option types Exercises [9 exercises with solution and Explanation]

[An editor is available at the bottom of the page to write and execute the scripts. Go to the editor]

1. Write a Rust function that returns an Option<String> representing the result of parsing a string into an integer.

Click me to see the solution

2. Write a Rust function that takes a vector of integers and returns the maximum value, return None if the vector is empty.

Click me to see the solution

3. Write a Rust function that reads a file and returns Result<String, std::io::Error>, where the string contains the file's contents.

Click me to see the solution

4. Write a Rust function that calculates the square root of a non-negative number and returns Option<f64>, where None is returned for negative inputs.

Click me to see the solution

5. Write a Rust function that parses a date string in the format "YYYY-MM-DD" and returns Result<(i32, u32, u32), &str> indicating the year, month, and day, or an error message.

Click me to see the solution

6. Write a Rust function that takes a string and returns Option<usize> representing the string length, returning None for empty strings.

Click me to see the solution

7. Write a Rust function that converts a hexadecimal string to an integer and returns Option<u64>, returning None for invalid input.

Click me to see the solution

8. Write a Rust function that divides two numbers and returns Result<f64, &'static str>, indicating success or division by zero error.

Click me to see the solution

9. Write a Rust function that filters odd numbers from a vector of integers and returns Option<Vec<i32>>, returning None if the input vector is empty.

Click me to see the solution

Rust Code Editor:

More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.



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/error_handling/result-and-option-types.php