我想要一组不同类型的结构。
Vec
不起作用,我认为因为不同的结构是不同的类型,Vec
只能包含一种类型。
struct Santa {
color: String,
phrase: String,
}
struct Rudolph {
speed: u32,
lumens: u32,
}
fn newSanta() -> Santa {
Santa {
color: String::from("Red"),
phrase: String::from("Ho ho ho!"),
}
}
fn newRudolph() -> Rudolph {
Rudolph {
speed: 100,
lumens: 500,
}
}
fn main() {
let santa = newSanta();
let rudolph = newRudolph();
let northerners = vec![santa, rudolph]; //fails
}
PS C:\Users\anon> rustc xmas.rs
error[E0308]: mismatched types
--> xmas.rs:27:32
|
27 | let northerners = vec![santa, rudolph]; //fails
| ^^^^^^^ expected struct `Santa`, found struct `Rudolph`
|
= note: expected type `Santa`
found type `Rudolph`
答案 0 :(得分:2)
通常的方法是为每种结构创建一个带有变体的enum
。处理它们时,您需要在其枚举变体上match
来确定它们的类型。
struct Santa {
color: String,
phrase: String,
}
struct Rudolph {
speed: u32,
lumens: u32,
}
fn newSanta() -> Santa {
Santa {
color: String::from("Red"),
phrase: String::from("Ho ho ho!"),
}
}
fn newRudolph() -> Rudolph {
Rudolph {
speed: 100,
lumens: 500,
}
}
enum Common {
Santa(Santa),
Rudolph(Rudolph),
}
fn main() {
let santa = newSanta();
let rudolph = newRudolph();
let northerners = vec![Common::Santa(santa), Common::Rudolph(rudolph)];
match &northerners[0] {
Common::Santa(santa) => println!("santa color: {}", santa.color),
Common::Rudolph(rudolph) => println!("rudolph speed: {}", rudolph.speed),
}
}
或者,如果他们每个人都实现了一个共同的特征,你可以存储trait objects个特征。