Rust 如何知道需要或提供哪些 trait 方法? [英] How does Rust know which trait methods are required or provided?
本文介绍了Rust 如何知道需要或提供哪些 trait 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
来自 std::iter::Iterator
文档,可以看到只需要next
方法:
所需方法
fn next(&mut self) -> Option<Self::Item>
但来自源代码,删除评论后:
pub trait Iterator {
/// The type of the elements being iterated over.
#[stable(feature = "rust1", since = "1.0.0")]
type Item;
......
#[stable(feature = "rust1", since = "1.0.0")]
fn next(&mut self) -> Option<Self::Item>;
......
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
......
}
我可以看到,除了 #[inline]
属性之外,必需方法和提供方法之间没有区别.Rust 如何知道需要或提供哪种方法?
I can see, except for the #[inline]
attribute, there is no difference between required and provided methods. How does Rust know which method is required or provided?
推荐答案
它相当简单:提供的(可选)函数有一个默认实现,而不是必需的.
It is rather simple: the provided (optional) functions have a default implementation, not the required.
请注意,如果您愿意,您可以重新实现提供的函数,以便它可以比特定结构/枚举的默认函数执行得更好.
Note that you can re-implement the provided functions if you wish so it can perform better than the default one for your particular struct/enum.
这篇关于Rust 如何知道需要或提供哪些 trait 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文