Created
September 15, 2015 20:27
-
-
Save roosmaa/6d4df8774341e060f1ee to your computer and use it in GitHub Desktop.
Dynamic method invocation in Rust
This file contains 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