Skip to content

Instantly share code, notes, and snippets.

@benw
Created June 18, 2013 02:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benw/5802109 to your computer and use it in GitHub Desktop.
Save benw/5802109 to your computer and use it in GitHub Desktop.
trait Fruit {
fn eat(&self);
}
struct Apple {
x: int
}
impl Fruit for Apple {
fn eat(&self) {
println(fmt!("Crunching on apple (%d)", self.x));
}
}
struct Banana {
y: int
}
impl Fruit for Banana {
fn eat(&self) {
println(fmt!("Munching on banana (%d)", self.y));
}
}
fn main() {
let managed: ~[ @Fruit ] = ~[
@Apple{ x: 1 } as @Fruit,
@Banana{ y: 2 } as @Fruit
];
let owned: ~[ ~Fruit ] = ~[
~Apple{ x: 1 } as ~Fruit,
~Banana{ y: 2 } as ~Fruit
];
println(~"This eats both fruit, as expected:");
for managed.each |fruit| {
fruit.eat();
}
println(~"This only eats the apple - why?!");
for owned.each |fruit| {
fruit.eat();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment