特性不能被做成一个对象 [英] The trait cannot be made into an object
问题描述
我有以下代码:
extern crate futures; // 0.1.24
use futures::Future;
use std::io;
struct Context;
pub trait MyTrait {
fn receive(context: Context) -> Future<Item = (), Error = io::Error>;
}
pub struct MyStruct {
my_trait: MyTrait,
}
当我尝试编译它时,我收到错误消息:
When I try to compile it I get the error message:
error[E0038]: the trait `MyTrait` cannot be made into an object
--> src/lib.rs:13:5
|
13 | my_trait: MyTrait,
| ^^^^^^^^^^^^^^^^^ the trait `MyTrait` cannot be made into an object
|
= note: method `receive` has no receiver
我想我知道它为什么会发生,但是我如何从结构中引用特征?是否可以?也许还有其他方法可以实现相同的行为?
I think I know why it happens, but how do I refer to the trait from the struct? Is it possible? Maybe there are other ways to implement the same behavior?
推荐答案
您可以向结构中添加类型参数,如 Zernike 的答案,或使用特征对象.
You can either add a type parameter to your struct, as in Zernike's answer, or use a trait object.
使用类型参数对性能更有利,因为 T
的每个值都会创建一个专门的结构副本,允许静态调度.trait 对象使用动态分派,因此它允许您在运行时交换具体类型.
Using the type parameter is better for performance because each value of T
will create a specialized copy of the struct, which allows for static dispatch. A trait object uses dynamic dispatch so it lets you swap the concrete type at runtime.
特征对象方法如下所示:
The trait object approach looks like this:
pub struct MyStruct<'a> {
my_trait: &'a dyn MyTrait,
}
或者这个:
pub struct MyStruct {
my_trait: Box<dyn MyTrait>,
}
但是,在您的情况下,MyStruct
不能成为对象,因为 receive
是一个静态方法.您需要更改它以将 &self
或 &mut self
作为它的第一个参数才能工作.还有其他限制.
However, in your case, MyStruct
cannot be made into an object because receive
is a static method. You'd need to change it to take &self
or &mut self
as its first argument for this to work. There are also other restrictions.
这篇关于特性不能被做成一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!