How can min_by_key or max_by_key be used with references to a value created during iteration?

前端 未结 1 1568
暗喜
暗喜 2021-01-16 14:25

I have an iterator that maps over some values, creating tuples on the way. I need to get the maximum by one of the elements on the tuple (which is not Copy

相关标签:
1条回答
  • 2021-01-16 15:14

    They cannot. As values flow through iterator adapters, they are moved. Moving a value causes any references to it to be invalidated. You are attempting to take a reference to a value that only exists in the iterator pipeline; the reference cannot live long enough. This is equivalent to this basic example:

    (0..9).map(|x| &x)
    

    You will need to use Iterator::min_by:

    v.iter().map(|i| (X(*i),)).min_by(|a, b| a.0.cmp(&b.0));
    

    This works because the returned value from the closure is an Ordering with no references to the original values.

    0 讨论(0)
提交回复
热议问题