为什么 len() 和 is_empty() 没有在特征中定义? [英] Why are len() and is_empty() not defined in a trait?

查看:26
本文介绍了为什么 len() 和 is_empty() 没有在特征中定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rust 中的大多数模式都被特征捕获(IteratorFromBorrow 等).

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

为什么像 len/is_empty 这样普遍的模式在标准库中没有关联的特征?这会导致我无法预见的问题吗?被认为是无用的吗?或者只是没有人想到它(这似乎不太可能)?

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

推荐答案

它是否被认为无用?

Was it deemed useless?

我猜这就是原因.

如果知道某物是空的或长度为 15,你能做什么?几乎什么都没有,除非你也有办法访问集合的元素.统一集合的特征是 Iterator.特别是迭代器可以告诉你它的底层集合有多少个元素,但它也能做更多的事情.

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.

另请注意,如果您需要 Empty trait,您可以创建一个并为所有标准集合实现它,这与大多数语言中的接口不同.这就是特质的力量.这也意味着标准库不需要为每个用例提供小的实用程序特征,它们可以由库提供!

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!

这篇关于为什么 len() 和 is_empty() 没有在特征中定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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