简体   繁体   English

Rust如何知道需要或提供哪些特征方法?

[英]How does Rust know which trait methods are required or provided?

From the std::iter::Iterator documentation, I can see that only the next method is required: std::iter::Iterator文档中,我可以看到只需要next方法:

Required Methods 所需方法

 fn next(&mut self) -> Option<Self::Item> 

But from the source code , after removing comments: 但是从源代码中 ,删除注释后:

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) }
    ......
}

I can see, except for the #[inline] attribute, there is no difference between required and provided methods. 我可以看到,除了#[inline]属性,必需方法和提供的方法之间没有区别。 How does Rust know which method is required or provided? Rust如何知道需要或提供哪种方法?

except for the #[inline] attribute, there is no difference between required and provided methods 除了#[inline]属性,必需方法和提供的方法之间没有区别

There is a huge difference, you just are ignoring the (lack of) formatting. 两者之间存在巨大差异,您只是忽略了格式的不足。 Allow me to reformat for you: 请允许我为您重新格式化:

fn next(&mut self) -> Option<Self::Item>;

fn size_hint(&self) -> (usize, Option<usize>) { // Starting with `{`
    (0, None)                                   //
}                                               // Ending with `}`

All the default methods have a function body . 所有默认方法都有一个函数体 The required methods do not. 所需的方法没有。

I'd highly recommend rereading The Rust Programming Language , specifically the chapter about traits and default implementations . 我强烈建议您重新阅读Rust编程语言 ,特别是有关特征和默认实现的章节 This resource is a much better way to get started with introductory topics like this than reading arbitrary snippets of the standard library. 与阅读标准库的任意代码片段相比,此资源是入门这类入门主题的更好方法。

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. 请注意,您可以根据需要重新实现所提供的功能,以使其比特定结构/枚举的默认功能更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM