Use trait for Iterator + Clone: conflicting implementations
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();
}
}
}
While it is compiling. However, when I additionally implement Foo
for another type like
impl Foo for u32 {
fn foo(self) { println!("{} u32", self); }
}
The following error message appears:
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?
source to share
The short answer is you can't. Since you cannot be sure that u32
there will be no implementation at some point Iterator
, the implementations do conflict. If you really want to implement it for Iterator
both u32
, you will have to make the implementations separate in some way. One way to do this is to implement it instead &'a FI
, as it u32
will never become a link. Alternatively, you can wrap the iterator in a structure, although this will make it somewhat less ergonomic to use.
source to share