Skip to content

Instantly share code, notes, and snippets.

@roosmaa
Created September 15, 2015 20:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save roosmaa/6d4df8774341e060f1ee to your computer and use it in GitHub Desktop.
Save roosmaa/6d4df8774341e060f1ee to your computer and use it in GitHub Desktop.
Dynamic method invocation in Rust
#![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