How to efficiently subtract equally named fields two vecs of structs

I am collecting a lot of data in a vec of structs.
I want to collect the same data a little later and efficiently calculate the differences based on that value in a certain field.
What would be the most efficient way?

I am thinking about saving the vec into another vec and then iterate over the oldest finding the same row in the earlier vec. Would there be a simpler way?

It is not clear what exactly you are trying to do. Please show actual code – abstract, generic descriptions usually don't help solve the problem.

1 Like

I'm a Rust noob so proceed with caution:

struct Test {
  value: f64

fn main() {
  let old = vec![Test { value: 2.0 }, Test { value: 5.0 }];
  let new = vec![Test { value: 2.5 }, Test { value: 7.0 }];
  let diffs: Vec<f64> = old
    .map(|i| i.1.value - i.0.value)
  println!("{:#?}", diffs)



I don't know if this is efficient or not but I think it does what you are describing.


Looks like decent Rust code to me. If you want, you can also use a pattern in the map, e.g.

.map(|(o, n)| n.value - o.value)

Also, if you want to save a few characters, you could use .zip(&new). In the future (in Rust 1.59 which will be release on 24th of February '22) you'll also be able to use std::iter::zip to write zip(&old, &new).map(...).collect() making this even more concise. Or you could use the same kind of function from itertools right now.


If this is indeed the desired result, then it doesn't seem to me like there is anything more efficient one could do.

@fritshoogland However, I suspect this is not what you are trying to do, because what you described seems to be more complicated, due to requiring some sort of matching between the rows. Is it so?

1 Like

As was requested, I created a playground example of the requested situation in a new topic, in which I tried describing the desired outcome better: Need help to show difference between statistics obtained as vec of structs

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.