为什么Rust类型中的所有索引都是usize? [英] Why are all indexes in Rust of type usize?

查看:2990
本文介绍了为什么Rust类型中的所有索引都是usize?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rust的 std :: ops :: Index< T> 仅支持 T usize 。这背后的原因是什么?

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

此外,当您尝试使用其他任何东西时,没有建议尝试使用usize,只是特性 [&'static str]:core :: ops :: Index< u8> 不满意错误。这可能是因为他们计划支持更多类型 T ,但由于某种原因推迟这样做?

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?

推荐答案


Rust的 std :: ops :: Index< T> 仅支持 T usize

这不是真的。例如, HashMap ,接受密钥类型可以借用的任何类型(因此您可以使用& str HashMap< String,_> $ c>)。

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).

切片只允许您使用 usize 对其进行索引,所有容器类型都假装是或实际 ,在内存中是线性的。那是因为 usize 是用于索引它们的正确的类型。任何其他类型将无法访问容器的完整潜在范围,或者将允许不可能存在的索引。

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.

这篇关于为什么Rust类型中的所有索引都是usize?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆