Why are all indexes in Rust of type usize?

前端 未结 1 1271
野的像风
野的像风 2020-12-20 17:14

Rust\'s std::ops::Index only supports T being a usize. What is the reason behind this?

Also, there is no advice to \

相关标签:
1条回答
  • 2020-12-20 17:20

    Rust's std::ops::Index<T> only supports T being a usize.

    This is just not true. HashMap, for example, accepts any type that the key type can borrow to (so you can index a HashMap<String, _> using a &str).

    Slices only allow you to index them using usize, as do all container types that either pretend to be, or actually are, linear in memory. That's because usize is the correct type with which to index them. Any other type would either not be able to access the full potential range of the container, or would allow for indices that cannot possibly exist.

    People have asked in the past about adding smaller types to slice indexing, but this would be backward-incompatible, so it's not going to happen any time soon.

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