gpt4 book ai didi

pattern-matching - 匹配复杂的继承-y 东西

转载 作者:行者123 更新时间:2023-11-29 08:14:40 31 4
gpt4 key购买 nike

我想在 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] 是 Player 枚举项时,我该怎么做才能获得 PlayerData?

最佳答案

一个解决方案,同时让您的设计保持新类型(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 */ },
}
}

(Playground)


但是,我宁愿为此利用特征系统:

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();
}

关于pattern-matching - 匹配复杂的继承-y 东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30488653/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com