Implement trait for Iterator+Clone: conflicting implementations

 

Questions


I want to implement a trait Foo for Iterator (i.e., for all types that implement Iterator), so I wrote this:

trait Foo {
    fn foo(&self);
}

impl<F, FI> Foo for FI
    where F: Foo,
          FI: Iterator<Item=F> + Clone,
{
    fn foo(&self) {
        // Just for demonstration
        for x in self.clone() {
            x.foo();
        }
    }
}

So far, it compiles. However, when I additionally implement Foo for another type, like

impl Foo for u32 {
    fn foo(self) { println!("{} u32", self); }
}

I get the following error message:

t.rs:5:1: 7:2 error: conflicting implementations for trait `Foo` [E0119]
t.rs:5 impl Foo for u32 {
t.rs:6     fn foo(self) { println!("{} u32", self); }
t.rs:7 }
t.rs:9:1: 18:2 note: note conflicting implementation here
t.rs:9 impl<F, FI> Foo for FI
t.rs:10     where F: Foo,
t.rs:11           FI: Iterator<Item=F> + Clone,
t.rs:12 {
t.rs:13     fn foo(&self) {
t.rs:14         for x in self.clone() {

How do I resolve this?

(Playground)

 

 

————————————————-

Answer

The short answer is, that you can’t. Since you can’t make sure that u32 won’t at some point implement Iterator, the implementations do indeed conflict. If you really want to implement it for both Iterator and u32, you’ll have to somehow make the implementations separate. One way to do this would be to implement it for &'a FI instead, since u32 can never become a reference. Alternatively you could wrap the iterator in a struct, though this would make it slightly less ergonomic to use.

rust

Facebook Comments

Post a comment