Why are len() and is_empty() not defined in a trait?

女生的网名这么多〃 提交于 2021-02-10 18:34:16

问题


Most patterns in Rust are captured by traits (Iterator, From, Borrow, etc.).

How come a pattern as pervasive as len/is_empty has no associated trait in the standard library? Would that cause problems which I do not foresee? Was it deemed useless? Or is it only that nobody thought of it (which seems unlikely)?


回答1:


Was it deemed useless?

I would guess that's the reason.

What could you do with the knowledge that something is empty or has length 15? Pretty much nothing, unless you also have a way to access the elements of the collection for example. The trait that unifies collections is Iterator. In particular an iterator can tell you how many elements its underlying collection has, but it also does a lot more.

Also note that should you need an Empty trait, you can create one and implement it for all standard collections, unlike interfaces in most languages. This is the power of traits. This also means that the standard library doesn't need to provide small utility traits for every single use case, they can be provided by libraries!



来源:https://stackoverflow.com/questions/60449514/why-are-len-and-is-empty-not-defined-in-a-trait

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