2017-06-20 208 views
0

std::iter::Iterator文件,我可以看到,只需要next方法:Rust如何知道需要或提供哪些特征方法?

所需的方法

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

但是从source code,后删除注释:

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如何知道需要或提供哪种方法?

回答

4

这很简单:提供的(可选)函数具有默认实现,而不是必需的。

请注意,如果您愿意,可以重新实现提供的函数,以便它可以比您的特定结构/枚举的默认函数更好地执行。

7

除了#[inline]属性,有需要和提供的方法

有一个巨大的差异之间没有什么区别,你只是被忽略(缺乏)格式。请允许我重新格式化您:

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

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

所有有一个函数体默认的方法。所需的方法不。

我强烈推荐重读The Rust Programming Language,特别是the chapter about traits and default implementations。与阅读标准库的任意片段相比,此资源是开始介绍此类主题的好方法。

相关问题