Skip to content

Instantly share code, notes, and snippets.

@hyone
Last active October 9, 2016 07:53
Show Gist options
  • Save hyone/02b81a2a176ca0ada59a3343b6787b79 to your computer and use it in GitHub Desktop.
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
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