类型“A"未实现特征“A" [英] The trait `A` is not implemented for the type `A`

查看:35
本文介绍了类型“A"未实现特征“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]

rustc 的版本是 rustc 1.0.0-beta.3 (5241bf9c3 2015-04-25) (built 2015-04-25).

推荐答案

问题在于方法 f 不是对象安全的,因为它是通用的,因此不能在特征对象.您将不得不强制其用户通过盒装关闭:

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() -> ()>);
}

我想知道为什么 Rust 首先允许 Box ,我预计那里会出现错误.而这个特定的错误确实具有误导性.我会提交一个关于此的错误.

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.

或者,您可以放弃 trait 对象以支持常规有界泛型,尽管这并不总是可行的.

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

这篇关于类型“A"未实现特征“A"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆