Rust match + enum vs C++ dynamic dispatch

Published 444d ago

 ayebear

Idiomatic Rust version of https://en.wikipedia.org/wiki/Dynamic_dispatch#Example_in_C++

// Idiomatic Rust version of https://en.wikipedia.org/wiki/Dynamic_dispatch#Example_in_C++
enum Pet {
    Dog,
    Cat,
}

impl Pet {
    fn speak(&self) {
        let msg = match self {
            Pet::Dog => "Woof!",
            Pet::Cat => "Meow!",
        };
        println!("{}", msg);
    }
}

fn main() {
    let fido = Pet::Dog;
    let simba = Pet::Cat;
    fido.speak();
    simba.speak();
}

3

Please login or sign up to comment and collaborate