In the previous challenge we converted a Result<T, E>
to an Option<T>
by using the .ok()
method, Rust provides us other mechanisms to convert an Option<T>
to a Result<T, E>
as well. In this challenge, you will learn how to use the .ok_or()
method to convert an Option<T>
to a Result<T, E>
.
Implement the function get_first_element
:
Vec<i32>
).i32
)..first()
method to retrieve the first element of the vector, this returns Option<&T>
.None
, convert it to a Result<T, E>
using the .ok_or()
method with the error message "Vector is empty"
."First element is below the minimum allowed value"
.Ok(T)
with the first element.If you're stuck, here are some hints to help you solve the challenge:
.ok_or()
method and propagate the error cleanly. e.g.
let first_element = numbers.first().ok_or("Vector is empty".to_string())?;