Vec of Structs to Vec of Structs.var?

I have a vec containing my struct. I am looking for a simpler way to get a vec from its properties.


struct Mine {
   a: f32,
   b: f32

pub fn main() {
   let all_mine = vec![Mine{a:1.0, b:0.1}, Mine{a:2.0, b:0.2}];
   custom_fn(all_mine.b) // Here all_mine.b should return [0.1, 0.2]

I know it is possible to do,

all_mine.iter().map(|mine| mine.b).collect()

But my application is quite bigger and many places I will have to do this. So, calling iter and map, reduces the legibility of the code. Other solution is to write a function using impl but thought it would be nice if there is any out of box implementation.

Something like,

//all_mine returns the vec elements and . operator applies to each element
// or all_mine.all().b

i guess you could use a macro like so:

but really i think you should probably stick to using map, because that's more idiomatic and makes the code more readable to everyone else.


Really thanks. I think the macro will work :slight_smile:

Note that each collect makes a new allocation, so it would be expensive to do this operation often. You can try to omit collect() and make the receiving function work on the iterator returned by map. Also consider storing your data as a struct of arrays (SoA). soa-derive helps to do that ergonomically.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.