簡體   English   中英

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

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

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

除了#[inline]屬性,必需方法和提供的方法之間沒有區別

兩者之間存在巨大差異,您只是忽略了格式的不足。 請允許我為您重新格式化:

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

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

所有默認方法都有一個函數體 所需的方法沒有。

我強烈建議您重新閱讀Rust編程語言 ,特別是有關特征和默認實現的章節 與閱讀標准庫的任意代碼片段相比,此資源是入門這類入門主題的更好方法。

這非常簡單:提供的(可選)功能具有默認實現,而不是必需的。

請注意,您可以根據需要重新實現所提供的功能,以使其比特定結構/枚舉的默認功能更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM