Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

casting

rust

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?

like image 885
ideasman42 Avatar asked Oct 22 '25 14:10

ideasman42


2 Answers

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.

like image 113
DK. Avatar answered Oct 25 '25 18:10

DK.


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.

like image 39
oli_obk Avatar answered Oct 25 '25 19:10

oli_obk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!