Junior — Senior
Creating your own Result type
livecode
Task condition
The task requires developing a custom Result type that will be used to pass the result of a function execution along with error information. Implement a structure Result<T, E>, where T is the data type in case of success, and E is the error type. Provide methods for creating successful results and error results, as well as methods for checking the state and retrieving nested values.
Requirements:
- Define a generic structure Result<T, E>.
- Implement constructors
ok(value: T) -> Result<T, E>anderr(error: E) -> Result<T, E>. - Add methods
is_ok() -> bool,is_err() -> bool. - Implement methods
unwrap() -> T(panics on error) andunwrap_err() -> E(panics on success). - Optionally, you can add methods
map,map_err, and other convenient functions.
Example usage (you can change variable names, but leave the code unchanged):
let success: Result<i32, &str> = Result::ok(42);
let failure: Result<i32, &str> = Result::err("error occurred");
assert!(success.is_ok());
assert!(!failure.is_ok());
let value = success.unwrap();
let err_msg = failure.unwrap_err();
This task is suitable for assessing skills in generics, error handling patterns, and basic API design principles.