I have an if
statement which needs to check for the existence of a value in a nested Option
. The statement currently looks like
if my_vec.get(0).is_some() && my_vec.get(0).unwrap().is_some() {
// My True Case
} else {
// My Else Case
}
I feel like this is an amateurish way of checking if this potential nested value exists. I want to maintain safety when fetching the Option
from the array as it may or may not exist, and also when unwrapping the Option
itself. I tried using and_then
and similar operators but haven't had any luck.
CodePudding user response:
I would check the length first and access it like a regular array instead of using .get(x)
unless there is some benefit in doing so (like passing it to something which expects an option).
if my_vec.len() > x && my_vec[x].is_some() {
// etc
}
Another option is to just match the value with an if let x = y
or full match
statement.
if let Some(Some(_)) = my_vec.get(x) {
// etc
}
The matches!
macro can also be used in this situation similarly to the if let
when you don't need to take a reference to the data.
if matches!(my_vec.get(x), Some(Some(_))) {
// etc
}
Or the and_then
version, but personally it is probably my least favorite since it is longer and gargles the intention.
if my_vec.get(x).and_then(|y| y.as_ref()).is_some() {
// etc
}
You can pick whichever one is your favorite. They all compile down to the same thing (probably, I haven't checked).