Skip to content

Instantly share code, notes, and snippets.

@gugahoa
Created March 7, 2019 13:53
Show Gist options
  • Save gugahoa/def27de3dfde273923821206666c3aa1 to your computer and use it in GitHub Desktop.
Save gugahoa/def27de3dfde273923821206666c3aa1 to your computer and use it in GitHub Desktop.
use downcast_rs::{impl_downcast, Downcast};
trait Command: Downcast {
fn execute(&self);
}
impl_downcast!(Command);
#[derive(Debug, PartialEq)]
enum Temperature {
Hot,
Cold,
}
impl Command for Temperature {
fn execute(&self) {
println!("Temperature Command!");
}
}
#[derive(Debug, PartialEq)]
enum Planet {
Earth,
Neptune,
}
impl Command for Planet {
fn execute(&self) {
println!("Planet Command!");
}
}
fn main() {
let a: Box<Command> = Box::new(Temperature::Hot);
let also_a: Box<Command> = Box::new(Temperature::Hot);
let not_a: Box<dyn Command> = Box::new(Temperature::Cold);
let b = a.downcast_ref::<Temperature>();
let also_b = also_a.downcast_ref::<Temperature>();
let not_b = not_a.downcast_ref::<Temperature>();
assert_eq!(b, also_b);
assert_ne!(b, not_b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment