Let's say I have type T
which is an array. It looks like there's no easy way (at a type level) to get the type or length. Would it make sense to have something like this in the stdlib:
impl<T, const N: usize> [T; N] {
type Element = T;
const LEN: usize = N;
}
It seems like this will be a common need when working with generic arrays. If you grep arrayvec's source for ::Item
or ::CAPACITY
(from their custom Array trait), you'll find them used dozens of times.
Today's real-world use case:
type PartialHash = [u8; 16];
fn partial_hash(data: &[u8]) -> PartialHash {
// hardcode the length :(
Sha256::digest(data)[..16].try_into().unwrap()
// get the length from the type :)
Sha256::digest(data)[..PartialHash::LEN].try_into().unwrap()
}
I'll bet the compiler can handle this already. Writing an extension trait works fine under min_const_generics: Playground link