3 ms·
Rust really doesn't do implicit numeric conversion, and I suspect it would be hard to retrofit. But you could write a function i(...) that promoted u8, etc, to
by ekidd 5y ago
Rust really doesn't do implicit numeric conversion, and I suspect it would be hard to retrofit. But you could write a function i(...) that promoted u8, etc, to usize:
v[i(my_u8_index)]
This could be implemented as a compile-time check, with no runtime errors. You'd have to limit which types you support as indices if you want to be portable to platforms with tiny pointers, of course.
I guess something like this might be useful inside of specialized library code that worked with lots of small vectors.
But in general, Rust heavily favors explicit over implicit in many areas. If you want lots of automatic implicit behavior, something like Scala might be a better choice?
- samhw 5y agoIf you were going to do that, it may be easier just to implement `Index`/`IndexMut` over `u8`/`u16`/.. for whatever type (newtype if necessary) you're indexing into. I suppose it's hard to say without context though.