问题
The 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 method), but I would prefer to be more general.
Is there a subtrait of Index
that specifies the len
method or in some other way reveals what range of indices is allowed?
回答1:
Is there a subtrait of
Index
that specifies thelen
method or in some other way reveals what range of indices is allowed?
To the best of my knowledge, not in the standard library.
I would note, though, that you seem to be under the misconception that:
Index
necessarily returns a result for a contiguous range of keysIndex
this contiguous range starts at 0
Both assumptions are necessary for len
to be useful here (since I suppose that you are interested in checking before calling []
where the key is in present).
So, in essence, you are asking for a hierarchy of traits:
Index
, which allows querying for an element by keyRangeIndex
, which allows querying for an element by key, and guarantees that the valid keys form a contiguous range;RangeIndex
could have arange
method returning aRange
of valid keysZeroBasedRangeIndex
, which allows querying for an element by numeric keys, and guarantees that the valid form a contiguous range starting from0
;ZeroBasedRangeIndex
could have alen
method returning the number of valid keys
And of course those would have to be duplicated for IndexMut
.
Note: for example, one could implement Index<K, Output=V>
for BTreeMap<K, V>...
来源:https://stackoverflow.com/questions/40532847/is-there-a-subtrait-of-index-that-specifies-the-len-method