Reputation: 17477
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?
Upvotes: 7
Views: 2179
Reputation: 431011
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.
Upvotes: 10
Reputation: 1562
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.
Upvotes: 16