简体   繁体   中英

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:

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. How does Rust know which method is required or provided?

except for the #[inline] attribute, there is no difference between required and provided methods

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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