Created
January 11, 2014 15:54
-
-
Save nata79/8372600 to your computer and use it in GitHub Desktop.
Rust traits method overloading (does not compile)
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
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