类型提示结构作为特征

Type hinting structs as traits

我有一个方法 (Journal.next_command()),其签名 return 是 Command 特征。在方法中,我试图 return 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

您目前无法 return 拆箱特征,它们需要包装在某种容器中。

fn next_command(&self) -> Box<Command> {
    Box::new(Jump { height: 2 })
}

这有效。