The trait `A` is not implemented for the type `A`

送分小仙女□ 提交于 2019-12-10 14:41:42

问题


I am trying to use a trait that has a function that takes a closure as argument, and then use it on a trait object.

trait A {
    fn f<P>(&self, p: P) where P: Fn() -> ();
}

struct B {
    a: Box<A>
}

impl B {
    fn c(&self) {
        self.a.f(|| {});
    }
}

This snippet generates the following error:

the trait `A` is not implemented for the type `A` [E0277]

The version of rustc is rustc 1.0.0-beta.3 (5241bf9c3 2015-04-25) (built 2015-04-25).


回答1:


The problem is that method f is not object-safe because it is generic, and hence it can't be called on a trait object. You will have to force its users to pass boxed closure:

trait A {
    fn f(&self, p: Box<Fn() -> ()>);
}

I wonder why Rust allows Box<A> in the first place, I would expect an error there. And this particular error is really misleading. I would file a bug about this.

Alternatively, you can discard trait objects in favor of regular bounded generics, though it is not always possible.



来源:https://stackoverflow.com/questions/30055356/the-trait-a-is-not-implemented-for-the-type-a

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!