I have a fixed-size array [T; SIZE]
of values of a type T that is ordered (it implements Ord
, but not necessarily Clone
or Default
). I would like to extract the smallest value of the array and drop all the others.
In nightly rust, I can use array::IntoIter
to achieve that, but if possible, I would like my code to compile on stable.
Currently, I'm using the following (playground):
// Don't call this function if T has a custom Drop implementation or invalid bit patterns
unsafe fn get_min<T: Ord>(mut arr: [T; SIZE]) -> T {
let (idx, _) = arr.iter().enumerate().min_by(|(_, x), (_, y)| x.cmp(y)).unwrap();
unsafe { replace(&mut arr[idx], MaybeUninit::uninit().assume_init()) }
}
Of course, I'm not very happy with that. Is there a solution that is safer, and maybe less verbose?
MaybeUninit::uninit().assume_init()
is never a correct thing to do. You're right not to be happy about this solution. – AbraxasT
implementsDrop
, this code will calldrop()
for uninitialized memory. – JemimahMaybeUninit::uninit().assume_init()
is UB even for trivial all-bit-patterns-valid non-drop Copy types likei32
. – Abraxas