Last active
October 9, 2016 07:53
-
-
Save hyone/02b81a2a176ca0ada59a3343b6787b79 to your computer and use it in GitHub Desktop.
Practice: lifetime qualifier added version of sample code at http://rustbyexample.com/trait.html
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
struct Sheep<'a> { naked: bool, name: &'a str } | |
trait Animal<'a> { | |
fn new(name: &'a str) -> Self; | |
fn name(&self) -> &str; | |
fn noise(&self) -> &str; | |
fn talk(&self) { | |
println!("{} says {}", self.name(), self.noise()); | |
} | |
} | |
impl <'a> Sheep<'a> { | |
fn is_naked(&self) -> bool { | |
self.naked | |
} | |
fn shear(&mut self) { | |
if self.is_naked() { | |
println!("{} is already naked...", self.name()); | |
} else { | |
println!("{} gets a haircut!", self.name); | |
self.naked = true; | |
} | |
} | |
} | |
impl <'a> Animal<'a> for Sheep<'a> { | |
fn new(name: &str) -> Sheep { | |
Sheep { name: name, naked: false } | |
} | |
fn name(&self) -> &str { | |
self.name | |
} | |
fn noise(&self) -> &str { | |
if self.is_naked() { | |
"baaaaah?" | |
} else { | |
"baaaaah!" | |
} | |
} | |
fn talk(&self) { | |
println!("{} pauses briefly... {}", self.name, self.noise()); | |
} | |
} | |
fn main() { | |
let mut dolly: Sheep = Animal::new("Dolly"); | |
dolly.talk(); | |
dolly.shear(); | |
dolly.talk(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment