Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way of getting a vector with a particular field, form a vector of structs?

Tags:

rust

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?

like image 667
chaoticsystem Avatar asked Nov 20 '25 04:11

chaoticsystem


1 Answers

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();
like image 116
orlp Avatar answered Nov 21 '25 22:11

orlp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!