我正在尝试实现这种模式:
use std::any::Any;
use std::fmt::Debug;
trait CommandHandler {
fn execute(&self, data: TCommand);
}
#[derive(Debug)]
struct FooCommand {}
struct FooCommandHandler {}
impl CommandHandler for FooCommandHandler {
fn execute(&self, data: FooCommand) {
println!(“Foo”);
}
}
#[derive(Debug)]
struct BarCommand {}
struct BarCommandHandler {}
impl CommandHandler for BarCommandHandler {
fn execute(&self, data: BarCommand) {
println!(“Bar”);
}
}
fn execute(command: T)
where
T: Any + Debug,
{
println!(“Command: {:?}”, command);
match (&command as &Any).downcast_ref::() {
Some(c) => (FooCommandHandler {}).execute(c),
None => {}
};
match (&command as &Any).downcast_ref::() {
Some(c) => (BarCommandHandler {}).execute(c),
None => {}
};
}
fn main() {
(FooCommandHandler {}).execute(FooCommand {});
(BarCommandHandler {}).execute(BarCommand {});
execute(FooCommand {});
execute(BarCommand {});
}
这不起作用:
error[E0308]: mismatched types
–> src/main.rs:37:51
|
37 | Some(c) => (FooCommandHandler {}).execute(c),
| ^ expected struct `FooCommand`, found &FooCommand
|
= note: expected type `FooCommand`
found type `&FooCommand`
error[E0308]: mismatched types
–> src/main.rs:41:51
|
41 | Some(c) => (BarCommandHandler {}).execute(c),
| ^ expected struct `BarCommand`, found &BarCommand
|
= note: expected type `BarCommand`
found type `&BarCommand`
如何以保留以下要求的方式实现execute()方法:
类型XCommand应该完全天生执行它的XCommandHandler。
可能存在CommandHandler的多个实现。
命令处理程序接收(并使用)具体的命令实例,而不是对它的引用(不可能重复发送命令)。
本质上,我有一个泛型函数fn foo(v: T),我想发送给一些具体的函数fn foo1(v: Foo),fn foo2(v: Bar);我该怎么做?
transmute是唯一的选择吗?
请注意,这与Any::downcast_ref所做的不同,后者从通用值v返回&Foo,而不是Foo。