Maybe the question is not entirely understandable, but is simple. Let’s say I have a Rust struct.
struct Person{
_id: u32,
name: String,
}
And a vector of such struct.
people: Vec<Person> = foo
Is there a nicer way of getting a vector with let’s say all Persons _id? My first instinct was just to writing a for loop.
let mut people_ids: vec<String> = vec![];
for person in people{
people_ids.push(person._id)
}
people_ids
And of course, it works.But if you are working with structs with multiple field and want to get multiple vectors of different fields, writing a for loop for each field becomes very repetitive. I wonder what is a better and more general way to do it?
First of all, you shouldn't start structure fields with underscore. That said, this works:
let people_ids: Vec<_> = people.iter().map(|p| p._id).collect();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With