Created
August 31, 2019 22:06
-
-
Save mvniekerk/b30b1c948ea0db0fa247ce3d0eb545d8 to your computer and use it in GitHub Desktop.
Rust - show how to return a trait
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait Handle { | |
fn handle(&self) -> String; | |
} | |
struct Command<T> { | |
pub payload: T | |
} | |
struct Jump { | |
pub how_high: i32 | |
} | |
struct Marco { | |
pub polo: String | |
} | |
impl Handle for Command<Jump> { | |
fn handle(&self) -> String { | |
format!("Jumping {}", self.payload.how_high) | |
} | |
} | |
impl Handle for Command<Marco> { | |
fn handle(&self) -> String { | |
format!("Polo: {:?}", self.payload.polo) | |
} | |
} | |
const JUMP: &str = "jump"; | |
const MARCO: &str = "marco"; | |
// Notice the Box<dyn X> | |
fn get_handler(cmd: &str) -> Option<Box<dyn Handle>> { | |
match cmd { | |
JUMP => Some(Box::new(Command { payload: Jump { how_high: 10 }})), | |
MARCO => Some(Box::new( Command { payload: Marco { polo: "polo".to_string() }})), | |
_ => None | |
} | |
} | |
fn main() { | |
assert_eq!(get_handler("jump").unwrap().handle(), "Jumping 10".to_string()); | |
assert_eq!(get_handler("marco").unwrap().handle(), "Polo: \"polo\"".to_string()); | |
assert_eq!(get_handler("Nothing").is_none(), true); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment