rustonaut / vec1

Rust `Vec<T>` wrapper that gurantees to contain at least 1 element
Apache License 2.0
88 stars 15 forks source link

Methods like max still return Option #25

Closed MarcelRobitaille closed 1 year ago

MarcelRobitaille commented 2 years ago

Is it possible for methods like max() to play nicely with a Vec1? Since we know there is at least one element, we should know there is a max.

Vec::max() is strange. It takes an argument. I assume the issue lies in the need to iterate the vector, but maybe there is some workaround.

vec1![1, 2, 3].into_iter().max(); // Some(3)
rustonaut commented 1 year ago

A bit late but there is now (v1.10) a length 1 aware reduce on Vec1 directly (as well as reduce_ref and reduce_mut).

E.g.: you can do stuff like:

// consumes the vec1 and returns the max element
let value: T = vec1.reduce(std::cmp::max)
// iterates over the vec1 and returns a ref to the max element
let value: &T =  vec1.reduce_ref(std::cmp::max)
// iterates over the vec1 and returns a mut ref to the max element
let value: &mut T = vec1.reduce_mut(std::cmp::max)