I am trying to iterate on on Option<Vec<>>
.
#[derive(Debug)]
pub struct Person {
pub name: Option<String>,
pub age: Option<u64>,
}
#[derive(Debug)]
pub struct Foo {
pub people: Option<Vec<Person>>,
}
Naively I am using
for i in foo.people.iter() {
println!("{:?}", i);
}
Instead of iterating over all the elements of the Vec
, I am actually displaying the whole Vec
. It is like I am iterating over the only reference of the Option
.
Using the following, I am iterating over the Vec
content:
for i in foo.people.iter() {
for j in i.iter() {
println!("{:?}", j);
}
}
I am not sure this is the most pleasant syntax, I believe you should unwrap the Option
first to actually iterate on the collection.
Then I don't see where you can actually use Option::iter
, if you always have a single reference.
Here is the link to the playground.
Option
has aniter
method that "iterates over the possibly contained value", i.e. provides either the single value in theOption
(if option isSome
), or no values at all (if the option isNone
). As such it is useful if you want to treat the option as a container whereNone
means the container is empty andSome
means it contains a single element.To iterate over the underlying element's values, you need to switch from
foo.people.iter()
to eitherfoo.people.unwrap().iter()
orfoo.people.unwrap_or_else(Vec::new).iter()
, depending on whether you want the program to panic or not to iterate when encounteringNone
people.Compilable example in the playground.