How to index vectors with integer types (besides u

2020-04-18 06:49发布

问题:

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.

Is there a way to index a vector in Rust without having to explicitly cast to usize every time? eg:

vector[some_u32 as usize];

Casting in single instances isn't a problem, its just tedious when needed frequently.

Is there a way to avoid having to cast here?

回答1:

No.

If it were your own type, you could implement Index<u32>, but it isn't and you can't.

If you're really, pathologically opposed to casting the index, you could write an adaptor type that does the cast, but that's getting a bit silly.



回答2:

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<MyIndex> for [MyValue] {
    type Output = MyValue;
    fn index(&self, idx: MyIndex) -> &MyValue {
        &self[idx.0 as usize]
    }
}

Now, you can index any array of MyValues 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.



标签: casting rust