Is there a subtrait of `Index` that specifies the `len` method?

元气小坏坏 提交于 2021-01-29 03:59:59

问题


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 the len 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:

  1. Index necessarily returns a result for a contiguous range of keys
  2. Index 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 key
  • RangeIndex, which allows querying for an element by key, and guarantees that the valid keys form a contiguous range; RangeIndex could have a range method returning a Range of valid keys
  • ZeroBasedRangeIndex, which allows querying for an element by numeric keys, and guarantees that the valid form a contiguous range starting from 0; ZeroBasedRangeIndex could have a len 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!