[英]Downcasting Rust Trait Combinations
我有兩個結構, Dog
和Cat
:
struct Dog {
weight: f64
}
struct Cat {
weight: f64
}
和兩個特征MakesSound
和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 }
}
我希望能夠將它們存儲在異構Vec
,然后利用它們的兩個特征
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);
}
}
我如何定義具有類型的print_weight
函數
fn print_weight(x: &HasWeight);
這樣我的函數就需要盡可能少的信息,但是我的Vec
是否存儲了盡可能多的信息?
我從上面的行取消注釋得到的錯誤是
error: non-scalar cast: `&Animal` as `&HasWeight`
這是一個具有HasWeight
特征的類型的print_weight
函數。 不幸的是,我對Rust缺乏經驗,無法告訴您為什么需要附加的?Sized
特征綁定。
fn print_weight<T: HasWeight + ?Sized>(thing: &T) {
println!("{}", thing.get_weight());
}
可以在循環內調用它,而無需進行任何強制轉換: print_weight(animal)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.