2017-06-20 207 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。與閱讀標準庫的任意片段相比,此資源是開始介紹此類主題的好方法。

相關問題