[英]The trait `A` is not implemented for the type `A`
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)
. rustc
的版本是rustc 1.0.0-beta.3 (5241bf9c3 2015-04-25) (built 2015-04-25)
。
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. 问题是方法
f
不是对象安全的,因为它是通用的,因此不能在特征对象上调用它。 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. 我想知道为什么Rust首先允许
Box<A>
,我希望那里有错误。 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. 或者,您可以丢弃特征对象以支持常规有界泛型,尽管并非总是可行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.