Trait for array indices?

Is there a standard trait for things that can be used as array indices? Like, I want my container to be usable with u8, u16, u32, u64 or usize indices, depending on how many items the user wants to put in the container, so that the indices stored in the container will take up as little space as possible. Right now I'm using From<usize> + Into<usize> + Copy. Edit: Nope, that doesn't work.

There is one, SliceIndex<[T]>, but it's only implemented for usize of the ones you listed. Other integer types can't be used to index slices. If you want to make a container that can be indexed by other types, and have a trait that represents it, you'll have to write your own.

Doing that right now. :frowning:

I wonder if there's any discussion about why Rust doesn't just implement From and Into for all the types that can be casted with as.

Edit: rust - Why is type conversion from u64 to usize allowed using `as` but not `From`? - Stack Overflow kind-of explains it.

1 Like

I think the point is that as stands out in the code as something that may do something surprising: treat this unsigned integer as signed, for instance. What happens when the signed value is close to maximum may be surprising.

Contrast that with From and Into which should never be surprising, but because they also can't fail, you're limited to conversions that we know will succeed in unsurprising ways based only on the types involved. We can say u64::from(x) if we know x is a u32 because it will always succeed unsurprisingly, but we can't if x is an i32 despite the fact that u64::from(8i32) would succeed unsurprisingly because u64::from(-8i32) must either fail (impossible) or be surprising (against convention).

1 Like

That said, once TryFrom stabilizes, we get get TryFrom impls for all types that can be converted via as.