Skip to content

Instantly share code, notes, and snippets.

@epequeno
Last active May 29, 2018 17:36
Show Gist options
  • Save epequeno/57b625e34f2ad51cc273a7284c438ae4 to your computer and use it in GitHub Desktop.
Save epequeno/57b625e34f2ad51cc273a7284c438ae4 to your computer and use it in GitHub Desktop.
enum/struct practice in rust
#[derive(Debug)]
struct Dog {
name: String
}
#[derive(Debug)]
struct Cat {
name: String
}
#[derive(Debug)]
struct Human {
name: String
}
impl Dog {
fn new(name: &str) -> Dog {
Dog {
name: String::from(name)
}
}
fn speak(&self) {
println!("woof!");
}
}
impl Cat {
fn new(name: &str) -> Cat {
Cat {
name: String::from(name)
}
}
fn speak(&self) {
println!("meow!");
}
}
impl Human {
fn new(name: &str) -> Human {
Human {
name: String::from(name)
}
}
fn speak(&self) {
println!("hello!");
}
}
#[derive(Debug)]
enum Animal {
Dog(Dog),
Cat(Cat),
Human(Human)
}
impl Animal {
fn speak(&self) {
match self {
Animal::Dog(d) => d.speak(),
Animal::Cat(c) => c.speak(),
Animal::Human(h) => h.speak()
}
}
}
fn main() {
let spot = Animal::Dog(Dog::new("Spot"));
let kitty_purry = Animal::Cat(Cat::new("Kitty Purry"));
let alice = Animal::Human(Human::new("Alice"));
spot.speak();
kitty_purry.speak();
alice.speak();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment