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.
2. Write a Rust function that takes a vector of integers and returns the maximum value, return None if the vector is empty.
3. Write a Rust function that reads a file and returns Result<String, std::io::Error>, where the string contains the file's contents.
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.
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.
6. Write a Rust function that takes a string and returns Option<usize> representing the string length, returning None for empty strings.
7. Write a Rust function that converts a hexadecimal string to an integer and returns Option<u64>, returning None for invalid input.
8. Write a Rust function that divides two numbers and returns Result<f64, &'static str>, indicating success or division by zero error.
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.
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.
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
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics