我有一个方法(Journal.next_command()
),其签名会返回Command
个特征。在方法中,我试图返回实现Jump
特征的Command
结构的实例:
trait Command {
fn execute(&self);
}
struct Jump {
height: u32,
}
impl Command for Jump {
fn execute(&self) {
println!("Jumping {} meters!", self.height);
}
}
struct Journal;
impl Journal {
fn next_command(&self) -> Command {
Jump { height: 2 }
}
}
fn main() {
let journal = Journal;
let command = journal.next_command();
command.execute();
}
无法使用以下错误进行编译:
src/main.rs:19:9: 19:27 error: mismatched types:
expected `Command`,
found `Jump`
(expected trait Command,
found struct `Jump`) [E0308]
src/main.rs:19 Jump { height: 2 }
^~~~~~~~~~~~~~~~~~
如何通知编译器Jump
实现Command
?
答案 0 :(得分:1)
此刻您无法返回未装箱的特征,需要将它们包装在某种容器中。
fn next_command(&self) -> Box<Command> {
Box::new(Jump { height: 2 })
}
这很有效。