-
-
Save dseeni/dac66ed7fe4515aa3cbfba138769ef8e to your computer and use it in GitHub Desktop.
Dynamic method invocation in Rust
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
| #![feature(plugin)] | |
| #![plugin(dynamic_gen)] | |
| extern crate dynamic; | |
| use dynamic::Object; | |
| #[protocol] | |
| trait Pet { | |
| fn speak(&self) -> String; | |
| } | |
| #[dynamic] | |
| #[conform(Pet)] | |
| struct Dog { | |
| name: &'static str, | |
| } | |
| impl Pet for Dog { | |
| fn speak(&self) -> String { | |
| format!("{}: Woof!", self.name) | |
| } | |
| } | |
| #[dynamic] | |
| #[conform(Pet)] | |
| struct Cat { | |
| name: &'static str, | |
| } | |
| impl Pet for Cat { | |
| fn speak(&self) -> String { | |
| if self.name == "Garfield" { | |
| format!("{}: Lasagna !", self.name) | |
| } else { | |
| format!("{}: Meow!", self.name) | |
| } | |
| } | |
| } | |
| fn main() { | |
| let pets: Vec<Box<Object>> = vec![ | |
| Box::new(Cat{ name: "Nermal" }), | |
| Box::new(Dog{ name: "Odie" }), | |
| Box::new(Cat{ name: "Garfield" }), | |
| ]; | |
| for pet in pets { | |
| println!("{}", Pet::proxy(&*pet).speak()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment