Here, let's walk through this code:
trait ToMyIterator: Iterator + Sized {
fn myfunction(self) -> MyIterator<Self> {
MyIterator::new(self)
}
}
impl<I: Iterator> for I {}
-
trait ToMyIterator: Iterator + Sized
You're saying that all types which implement ToMyIterator
must also implement Iterator
, and be sized.
-
fn myfunction(self) -> MyIterator<Self> {
MyIterator::new(self)
}
A trait function with a default method implementation (please run your code through rustfmt in the future please!).
-
impl<I: Iterator> for I {}
This line, as it is, makes no sense, but I assume you meant something like this:impl<I: Iterator> ToMyIterator for I {}
Note that this means that all types which implement Iterator
, will also now implement your ToMyIterator
trait. This is, to some effect, extending the Iterator
trait, since you're doing such a broad blanket implementation.
Now, about your other code examples:
impl ToMyIterator for Iterator {}
This is technically equivalent to
impl ToMyIterator for dyn Iterator {}
Since in type position (which is to the right of for
in impl Trait for Type
), trait names are automatically assumed to be trait objects (dyn Trait
), however it's bad practice to omit the dyn
and will eventually become a hard error.
If you were asking about literally "extending" the stdlib iterator trait, you can't. Traits defined in other crates cannot be changed, and instead you can only do a blanket implementation, so that you are emulating the extension.
Finally, your last example:
impl ToMyIterator for dyn Iterator {}
Would be implementing your trait for the trait object. dyn Iterator
represents "some value of unknown type which implements the Iterator
trait". Implementing it like so would result in the implementation only applying to values which have been cast into a trait object. Note that I can do this:
trait Foo {
fn print(&self);
}
impl Foo for usize {
fn print(&self) {
println!("We're printing for usize");
}
}
impl Foo for dyn Debug {
fn print(&self) {
println!("We're printing for dyn Debug");
}
}
fn main() {
let x = 0usize;
x.print(); // We're printing for usize
(&x as &dyn Debug).print(); // We're printing for dyn Debug
}
Playground.