简体   繁体   中英

Type hinting structs as traits

I have a method ( Journal.next_command() ) who's signature returns the Command trait. In the method I am attempting to return an instance of the Jump struct, which implements the Command trait:

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();
}

This fails to compile with the following error:

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 }
                       ^~~~~~~~~~~~~~~~~~

How do I inform the compiler that Jump implements Command ?

You can't return unboxed traits at the moment, they need to be wrapped in some sort of container.

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

This works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM