是否有指定 len 方法的 `Index` 子特征?
Is there a subtrait of `Index` that specifies the `len` method?
std::ops::Index
trait is implemented by types that support array subscript notation. It appears that most types that implement Index
also have a len
method, but it is not part of the trait so you can't assume it exists. Therefore, I find myself writing code specialized for slices (which do have a len
方法),但我希望更通用。
是否有 Index
的子特征指定 len
方法或以其他方式揭示允许的索引范围?
Is there a subtrait of Index
that specifies the len
method or in some other way reveals what range of indices is allowed?
据我所知,不在标准库中。
不过,我要指出的是,您似乎误以为:
Index
必须 returns 连续键范围的结果
Index
这个连续范围从 0 开始
这两个假设对于 len
在这里有用是必要的(因为我想您有兴趣在 调用 []
之前检查 关键是目前)。
所以,本质上,你是在要求一个特征层次结构:
Index
,允许通过键 查询元素
RangeIndex
,允许通过key查询一个元素,并保证有效的key组成一个连续的范围; RangeIndex
可以有一个 range
方法返回 Range
个有效键
ZeroBasedRangeIndex
,允许通过数字键查询元素,并保证有效形式从0
开始的连续范围; ZeroBasedRangeIndex
可以有一个 len
方法返回有效键的数量
当然 IndexMut
.
必须重复这些
注意:例如,可以为 BTreeMap<K, V>
...
实施 Index<K, Output=V>
std::ops::Index
trait is implemented by types that support array subscript notation. It appears that most types that implement Index
also have a len
method, but it is not part of the trait so you can't assume it exists. Therefore, I find myself writing code specialized for slices (which do have a len
方法),但我希望更通用。
是否有 Index
的子特征指定 len
方法或以其他方式揭示允许的索引范围?
Is there a subtrait of
Index
that specifies thelen
method or in some other way reveals what range of indices is allowed?
据我所知,不在标准库中。
不过,我要指出的是,您似乎误以为:
Index
必须 returns 连续键范围的结果Index
这个连续范围从 0 开始
这两个假设对于 len
在这里有用是必要的(因为我想您有兴趣在 调用 []
之前检查 关键是目前)。
所以,本质上,你是在要求一个特征层次结构:
Index
,允许通过键 查询元素
RangeIndex
,允许通过key查询一个元素,并保证有效的key组成一个连续的范围;RangeIndex
可以有一个range
方法返回Range
个有效键ZeroBasedRangeIndex
,允许通过数字键查询元素,并保证有效形式从0
开始的连续范围;ZeroBasedRangeIndex
可以有一个len
方法返回有效键的数量
当然 IndexMut
.
注意:例如,可以为 BTreeMap<K, V>
...
Index<K, Output=V>