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

前端 未结 2 1061
情书的邮戳
情书的邮戳 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 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.

提交回复
热议问题