我有一种复杂的继承 - 我想在Rust中匹配它:
struct Entity {
pub kind: EntityKind,
}
pub enum EntityKind {
Player(PlayerData),
}
pub struct PlayerData {
pub name: String,
}
如何将它与模式匹配的东西相匹配,例如:
// pretend theres a vector of entities called E
match E[i] {
// match PlayerKind,
// match another kind here
}
我如何做到这一点,以便当E [i]是玩家枚举项目时我可以获得PlayerData?
答案 0 :(得分:3)
使用newtypes保持设计的解决方案(learn more about newtypes):
struct Entity {
pub kind: EntityKind,
}
pub enum EntityKind {
Player(PlayerData),
Weapon(WeaponData),
}
pub struct PlayerData {
pub name: String,
}
pub struct WeaponData {
pub damage_per_shot: i32,
}
fn f(e: EntityKind) {
match e {
EntityKind::Player(player_data) => { /* do sth with player data */ },
EntityKind::Weapon(weapon_data) => { /* do sth with weapon data */ },
}
}
但是,我宁愿利用特质系统:
struct Entity {
pub kind: EntityKind,
}
pub trait EntityKind {
fn do_something(&self); // or &mut self, if needed
}
pub struct PlayerData {
pub name: String,
}
impl EntityKind for PlayerData {
fn do_something(&self) {
// do sth with player data
}
}
pub struct WeaponData {
pub damage_per_shot: i32,
}
impl EntityKind for WeaponData {
fn do_something(&self) {
// do sth with weapon data
}
}
// Dynamic dispatch version
fn f(e: &EntityKind) {
e.do_something();
}
// Static dispatch version (a la C++ template)
fn g<E: EntityKind>(e: E) {
e.do_something();
}