Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Rust traits method overloading (does not compile)
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.