#Best way to resolve this?

1 messages · Page 1 of 1 (latest)

simple needle
#
    let deads: Vec<((usize, _), _)> = beings
        .thirsts
        .iter()
        .enumerate()
        .zip(beings.hungers.iter())
        .filter(|((_, hunger), thirst)| **hunger < 1 || **thirst < 1)
        // .map(|((id, _), _)| id)
        .collect();

This tuple ends up keeping references to beings.hungers and beings.thirsts that I don't need and which are causing borrow issues.

I can map them out with the commented out line, or I could clone them before iterating on them; both seem to work, but both seem to be wasteful. Can someone tell me a more correct approach? Thanks!

ember pawn
#

these are all numbers, right?

#

so what you want to do is discard the references asap, i.e. add .copied() after each .iter()

#

then your iteration result (whether or not you collect it) will be free of references

#

you can also then do the map and the filter with only one match, like this:

     let deads: Vec<usize> = beings
        .thirsts
        .iter()
        .copied()
        .enumerate()
        .zip(beings.hungers.iter().copied())
        .filter_map(|((id, hunger), thirst)| (hunger < 1 || thirst < 1).then_some(id))
        .collect();
simple needle
#

Thanks a lot! I wasn't aware of copied , I was using clone to accomplish the same thing. I'm going to have to look into the distinction between the two, but in the meantime I'm glad to know I'm using a more correct solutions.

ember pawn
#

iterators have .cloned() and .copied() which mean "clone/copy each element"

#

so .copied() is useful whenever you have numbers or some other Copy type that doesn't need to be taken by reference, and in either case, it avoids allocating a new vector as thirsts.clone().into_iter() would