Pre²-RFC: Get an array's type/length at a type level

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

6 Likes

Unfortunately, normal impls can't have associated types, so you can't have type Element.

That restriction should just be lifted, I don't see any reason to forbid them there

4 Likes

Yes, I was just noting a current restriction. It should be lifted.

Oh right, I forgot about that restriction. I guess we can revisit this sometime in the future.

This isn't a huge priority anyway, since you can DIY in userland