How to get min_by_key in iter_mut()

There is a slice of elements of Type T which implements Ord.
I'm trying to do this:
slice.iter_mut().enumerate().min_by_key(|(_, t)| t)
its fails to compile
However if I do this:
slice.iter_mut().min()
it compiles.
But the thing is I want the index of the element along with the mutable reference of the minimum. That's why I need enumerate() method also.
I tried different ways also:

|&(_, t)| &t
|(_, t)| &**t
|&(_, t)| t

all of them give compiler errors which are either data is moved or the reference is trying to outlive its lifetime.
How to do this?

The "key" returned from the closure you provide to min_by_key will be stored in a variable that outlives the closure invocation itself. Therefore, you can't pass min_by_key a closure that returns a reference to its input, since that would allow min_by_key to "smuggle" a short-lived reference into a (relatively) long-lived variable. Probably the best way to understand why this is, is to try to implement min_by_key yourself -- you will find that in order to avoid calling f twice as often as necessary, you must give it a return type that does not borrow from the item.

Just use min_by(|(_, a), (_, b)| a.cmp(b)).

1 Like

Thanks for the explanation.

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.