/******************************************************************************
Online Rust Compiler.
Code, Compile, Run and Debug Rust program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
use std::vec;
trait HasWeight {
fn weight(&self) -> u32;
}
struct Cat {}
impl HasWeight for Cat {
fn weight(&self) -> u32 {
42
}
}
struct Dog {}
impl HasWeight for Dog {
fn weight(&self) -> u32 {
9001
}
}
struct CatDog {
cat: Cat,
dog: Dog,
}
impl HasWeight for CatDog {
fn weight(&self) -> u32 {
self.cat.weight() + self.dog.weight()
}
}
fn printWeights(xs: Vec<&dyn HasWeight>) {
for x in xs.iter() {
println!("{}", x.weight());
}
}
fn main() {
let cat = Cat{};
let dog = Dog{};
let catdog = CatDog{ cat: Cat{}, dog: Dog{} };
let mut pets: Vec<&HasWeight> = Vec::new();
pets.push(&cat);
pets.push(&dog);
pets.push(&catdog);
printWeights(pets);
}