【发布时间】:2021-11-06 05:49:30
【问题描述】:
我正在尝试实现以下特征和结构:
pub trait Funct {
fn arity(&self) -> u32;
}
#[derive(Debug, Hash, Eq, PartialEq, Clone)]
pub struct FunctionLiteral<T: Funct> {
pub function: T,
pub args: Vec< FunctionLiteral<T> >
}
pub enum Foo {
Foo
}
impl Funct for Foo {
fn arity(&self) -> u32 {0}
}
pub enum Bar {
Bar
}
impl Funct for Bar {
fn arity(&self) -> u32 {0}
}
fn main() {
let baz = FunctionLiteral{
function: Foo::Foo,
args: vec![FunctionLiteral{
function: Bar::Bar,
args: vec![]
}]
};
}
我可以按照我对泛型类型 T 的方式进行设置,使其具有特征 Funct,但我不一定希望 T 具有相同的类型。
这里,编译代码会出现以下错误:
error[E0308]: mismatched types
--> foo.rs:31:23
|
31 | function: Bar::Bar,
| ^^^^^^^^ expected enum `Foo`, found enum `Bar`
error: aborting due to previous error
是否可以设置FunctionLiteral 以便我可以为function 和args 的项目设置不同的类型,同时强制它们都为Funct 类型?
【问题讨论】:
-
是的,你应该
Box他们 -
Box<dyn Funct>特别是。那么FunctionLiteral甚至不需要是通用的。见doc.rust-lang.org/book/ch17-02-trait-objects.html