rust - Type hinting structs as traits -


i have method (journal.next_command()) who's signature returns command trait. in method attempting return instance of jump struct, implements command trait:

trait command {     fn execute(&self); }  struct jump {     height: u32, }  impl command 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 compile 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 inform compiler jump implements command?

you can't return unboxed traits @ moment, need wrapped in sort of container.

fn next_command(&self) -> box<command> {     box::new(jump { height: 2 }) } 

this works.


Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -