Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
700 views
in Technique[技术] by (71.8m points)

indexing - Why are all indexes in Rust of type usize?

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

Also, there is no advice to "try using usize" when you attempt to use anything else, just a "trait [&'static str]: core::ops::Index<u8> not satisfied" error. Is this maybe because they plan to support more types T, but delayed doing so for some reason?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...