Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Rust traits method overloading (does not compile)

View gist:8372600
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
trait BalancedEater {
fn eat(&self) -> Self;
}
 
trait CrazyEater {
fn eat(&self) -> Self;
}
 
struct CookiesMonster {
cookies: int,
hungry_level: int
}
 
impl BalancedEater for CookiesMonster {
fn eat(&self) -> CookiesMonster {
if self.cookies >= self.hungry_level {
let new_cookies = self.cookies - self.hungry_level;
return CookiesMonster { cookies: new_cookies, hungry_level: 0 };
} else {
let new_hungry_level = self.hungry_level - self.cookies;
return CookiesMonster { cookies: 0, hungry_level: new_hungry_level };
}
}
}
 
impl CrazyEater for CookiesMonster {
fn eat(&self) -> CookiesMonster {
let mut new_hungry_level: int;
if self.cookies >= self.hungry_level {
new_hungry_level = 0
} else {
new_hungry_level = self.hungry_level - self.cookies;
}
 
return CookiesMonster { cookies: 0, hungry_level: new_hungry_level };
}
}
 
fn main() {
let cm = CookiesMonster { cookies: 10, hungry_level: 5 };
let new_cm = cm.eat();
println!("{:?}", new_cm)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.