Created
June 28, 2024 13:36
-
-
Save zanshin/db7063f23666e6769b663caf6d16c1c1 to your computer and use it in GitHub Desktop.
Using enums and traits to mimic inheritance in Rust
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
[package] | |
name = "inheritance" | |
version = "0.1.0" | |
edition = "2021" | |
[dependencies] | |
strum = { version = "0.26.3", features = ["derive"] } |
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
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(); | |
} | |
} |
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
Code suggested by this YouTube short: https://www.youtube.com/shorts/Fze6w1LbDmc