Skip to content

Instantly share code, notes, and snippets.

@zanshin
Created June 28, 2024 13:36
Show Gist options
  • Save zanshin/db7063f23666e6769b663caf6d16c1c1 to your computer and use it in GitHub Desktop.
Save zanshin/db7063f23666e6769b663caf6d16c1c1 to your computer and use it in GitHub Desktop.
Using enums and traits to mimic inheritance in Rust
[package]
name = "inheritance"
version = "0.1.0"
edition = "2021"
[dependencies]
strum = { version = "0.26.3", features = ["derive"] }
use strum::*;
#[derive(Default)]
struct Cat;
#[derive(Default)]
struct Dog;
#[derive(Default)]
struct Duck;
#[derive(EnumIter)]
enum Pet {
Cat(Cat),
Dog(Dog),
Duck(Duck),
}
trait Noise {
fn noise(&self);
}
impl Noise for Pet {
fn noise(&self) {
match self {
Pet::Cat(cat) => cat.noise(),
Pet::Dog(dog) => dog.noise(),
Pet::Duck(duck) => duck.noise(),
}
}
}
impl Noise for Cat {
fn noise(&self) {
println!("meow");
}
}
impl Noise for Dog {
fn noise(&self) {
println!("woof");
}
}
impl Noise for Duck {
fn noise(&self) {
println!("quack");
}
}
fn main() {
for animal in Pet::iter() {
animal.noise();
}
}
@zanshin
Copy link
Author

zanshin commented Jun 28, 2024

Code suggested by this YouTube short: https://www.youtube.com/shorts/Fze6w1LbDmc

@zanshin
Copy link
Author

zanshin commented Jun 28, 2024

Sample run:

❯ cargo run
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.08s
     Running `target/debug/inheritance`
meow
woof
quack

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment