How should I go about reading the value that's nested within two Option
s?
I have this code:
struct Person<T> {
name: &'static str,
preferences: Vec<&'static str>,
variant: Option<T>,
}
struct Driver {
seats: usize,
}
fn main() {
let list: Vec<Person<Driver>> = todo!();
let name = "some-name";
// add a bunch of Person<Driver> drivers to the `list`
let found = list.iter().find(|candidate| candidate.name == name);
// other things
}
What's the cleanest or most recommended way to access the field seats
from Option<Person<Driver>>
in found
?
The two ways I've done it is with a nested if let
or a nested match
. The nested match
looks a little ugly, so this is what I'm going with:
if let Some(person) = found {
if let Some(driver) = &person.variant {
println!("{:?}", driver.seats);
}
}
Is there a better way of going about it?
The reason I have an Option
field called variant
is since I also have Rider
structs and they're literally just a Person
. Since both drivers and riders have almost all the same fields, I structured it this way instead of opting to say a person: Person
field in each Rider
and Driver
struct which felt odd.