NLinker icon

Dynamic dispatch in Rust

NLinker | PRO | 10/20/24 08:38:41 AM UTC (Edited) | 0 ⭐ | 1363 👁️ | Never ⏰ | []
Rust |

800 B

|

None

|

0 👍

/

0 👎

// https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=8fb2d746bd9e13e735dcfc5cef97713f
// https://imgur.com/a/osZgl :-)
 
trait Animal {
    fn sound(&self);
}
 
#[derive(Debug)]
enum Color {
    White,
    Black,
    Grey,
}
 
struct Cat {
    color: Color,
}
impl Animal for Cat {
    fn sound(&self) { println!("Meow: {:?}", self.color) }
}
 
 
struct Dog {
    kind: i32,
}
impl Animal for Dog {
    fn sound(&self) { println!("Wuff: {}", self.kind) }
}
 
fn main() {
    let cat1 = Cat { color: Color::White };
    let cat2 = Cat { color: Color::Black };
    let cat3 = Cat { color: Color::Grey };
    let dog = Dog { kind: 2 };
    let animals: Vec<&dyn Animal> = vec![&cat1, &cat2, &cat3, &dog];
    for animal in animals {
        animal.sound();
    }
}

Comments