There are times when indices need to be tightly packed (mesh geometry for example), where its useful to store indices as u32
instead of usize
.
If you only want to index arrays of your own type, and you use a newtype for the index, then you can create an Index
impl:
struct MyIndex(u32);
struct MyValue(u64);
impl std::ops::Index for [MyValue] {
type Output = MyValue;
fn index(&self, idx: MyIndex) -> &MyValue {
&self[idx.0 as usize]
}
}
Now, you can index any array of MyValue
s with MyIndex
. Instead of using u32
everywhere, you now have to use MyIndex
. There's the newtype_derive crate to help you make the MyIndex
behave mostly like a u32
.