Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

rust - How can I iterate on an Option<Vec<_>>?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As mentioned in comments to another answer, I would use the following:

// Either one works
foo.people.iter().flatten()
foo.people.iter().flat_map(identity)

The iter method on Option<T> will return an iterator of one or zero elements.

flatten takes each element (in this case &Vec<Person>) and flattens their nested elements.

This is the same as doing flat_map with identity, which takes each element (in this case &Vec<Person>) and flattens their nested elements.

Both paths result in an Iterator<Item = &Person>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...