2 ms·
FWIW, you can have a newtype wrapper around Vec that provides indexing access with any type you want. If you are porting or writing code that uses i32 for indic
by estebank 4y ago
FWIW, you can have a newtype wrapper around Vec that provides indexing access with any type you want. If you are porting or writing code that uses i32 for indices for some reason, then you use the wrapper instead of Vec with no runtime cost and no inline type conversions.
This hasn't been solved at the language level yet because if we `impl Idx for u8` then inference in `vec[42]` breaks. Making inference support that in a principled manner will require a lot of work, and doing it in a hacky way might lock us into a suboptimal place that we haven't fully explored yet. I want to see some solution here at some point.
- colejohnson66 4y agoYou wouldn’t have to ‘impl Idx for u8’ if implicit upconversion was a thing. If it was, we could do this with no issues: let idx: u8 = 42; let val = vec[idx]; As GP said, the current “solution” is to do ‘idx as usize’ which is verbose.