How to index vectors with integer types (besides usize), without explicit cast?

前端 未结 2 1062
情书的邮戳
情书的邮戳 2021-01-21 13:53

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.

相关标签:
2条回答
  • 2021-01-21 14:19

    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.

    0 讨论(0)
  • 2021-01-21 14:34

    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.

    0 讨论(0)
提交回复
热议问题