I have two structs, Dog
and Cat
:
struct Dog {
weight: f64
}
struct Cat {
weight: f64
}
and two traits MakesSound
and HasWeight
trait MakesSound {
fn make_sound(&self);
}
impl MakesSound for Dog {
fn make_sound(&self) {
println!("Bark bark!");
}
}
impl MakesSound for Cat {
fn make_sound(&self) {
println!("Go away.");
}
}
trait HasWeight {
fn get_weight(&self) -> f64;
}
impl HasWeight for Dog {
fn get_weight(&self) -> f64 { self.weight }
}
impl HasWeight for Cat {
fn get_weight(&self) -> f64 { self.weight }
}
I would like to be able to store them in a heterogeneous Vec
and then make use of both their traits
trait Animal: MakesSound + HasWeight {}
impl<T: MakesSound + HasWeight> Animal for T {}
fn main() {
let dog = Dog{ weight: 45.0 };
let cat = Cat{ weight: 12.0 };
let animals: Vec<&Animal> = vec![&dog, &cat];
for animal in animals {
animal.make_sound();
println!("{}", animal.get_weight());
//print_weight(animal as &HasWeight);
}
}
How would I define a print_weight
function that had type
fn print_weight(x: &HasWeight);
so that my function would require as little information as possible, but my Vec
is storing as much information as possible?
The error I get from uncommenting the line above is
error: non-scalar cast: `&Animal` as `&HasWeight`