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

Rust如何知道需要或提供哪些特征方法?,rust,Rust,从文档中,我可以看到只需要next方法: 必要的方法 fn next(&mut self) -> Option<Self::Item> fn下一步(&mut self)->选项 但在删除注释后,从中: pub trait Iterator { /// The type of the elements being iterated over. #[stable(feature = "rust1", since = "1.0.0")] type

从文档中,我可以看到只需要
next
方法:

必要的方法

fn next(&mut self) -> Option<Self::Item>
fn下一步(&mut self)->选项
但在删除注释后,从中:

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) }
    ......
}
pub特征迭代器{
///正在迭代的元素的类型。
#[稳定(feature=“rust1”,since=“1.0.0”)]
类型项目;
......
#[稳定(feature=“rust1”,since=“1.0.0”)]
fn next(&mut self)->选项;
......
#[内联]
#[稳定(feature=“rust1”,since=“1.0.0”)]
fn size_hint(&self)->(usize,Option){(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 `}`
fn next(&mut self)->选项;
fn size_hint(&self)->(usize,Option){//以开头`{`
(0,无)//
}//以`}结尾`
所有默认方法都有一个函数体。所需的方法不适用

我强烈建议重读,尤其是。与阅读标准库中的任意代码片段相比,本资源是一种更好的入门方法