特质不能成为对象 [英] 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.
使用type参数可以提高性能,因为T
的每个值都会创建该结构的专用副本,从而可以进行静态分派.特质对象使用动态调度,因此可以在运行时交换具体类型.
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.
特征对象方法如下:
pub struct MyStruct<'a> {
my_trait: &'a dyn MyTrait,
}
或者这个:
pub struct MyStruct {
my_trait: Box<dyn MyTrait>,
}
但是,在您的情况下,由于receive
是静态方法,因此无法将MyStruct
制成对象.您需要将其更改为采用&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屋!