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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…