实现Iterator + Clone的特征:冲突的实现

Adr*_*her 3 rust

我想实现一个特质FooIterator(即,为实现所有类型Iterator),所以我写了这一点:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,它编译.但是,当我另外实现Foo另一种类型时,比如

impl Foo for u32 {
    fn foo(self) { println!("{} u32", self); }
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误消息:

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() {
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

(操场)

小智 5

简短的回答是,你做不到.由于您无法确保u32在某些时候不会实现Iterator,因此实现确实会发生冲突.如果你真的想要实现它都Iteratoru32,你必须以某种方式使实现分离.实现此目的的一种方法是实现它&'a FI,因为u32永远不能成为参考.或者,您可以将迭代器包装在结构中,但这会使其使用时略微不符合人体工程学.