Rust 如何在不同的板条箱中将枚举分成两部分?

Rust 如何在不同的板条箱中将枚举分成两部分?,rust,Rust,以下是我的出发点: #[derive(PartialEq)] enum ControlItem { A { name: &'static str, }, B { name: &'static str, }, } struct Control { items: Vec<(ControlItem, bool)>, } impl Control { pub fn set(&mut s

以下是我的出发点:

#[derive(PartialEq)]
enum ControlItem {
    A {
        name: &'static str,
    },
    B {
        name: &'static str,
    },
}

struct Control {
    items: Vec<(ControlItem, bool)>,
}

impl Control {
    pub fn set(&mut self, item: ControlItem, is_ok: bool) {
        match self.items.iter().position(|ref x| (**x).0 == item) {
            Some(idx) => {
                self.items[idx].1 = is_ok;
            }
            None => {
                self.items.push((item, is_ok));
            }
        }
    }

    pub fn get(&self, item: ControlItem) -> bool {
        match self.items.iter().position(|ref x| (**x).0 == item) {
            Some(idx) => return self.items[idx].1,
            None => return false,
        }
    }
}

fn main() {
    let mut ctrl = Control { items: vec![] };
    ctrl.set(ControlItem::A { name: "a" }, true);
    assert_eq!(ctrl.get(ControlItem::A { name: "a" }), true);
    ctrl.set(ControlItem::B { name: "b" }, false);
    assert_eq!(ctrl.get(ControlItem::B { name: "b" }), false);
}
  • 我希望
    控件
    具有
    获取
    /
    设置
    方法,这些方法只接受名称为
    项1
    项2
    项3
    的对象

  • 我想把这个虚拟桌子放在两个板条箱里:“主”和“平台”。大部分
    控制的实现
    应放在主板条箱中,项目的定义(如
    项目_3
    )应放在平台板条箱中。我想在编译时注册
    项3


  • 关于如何实现这一点有什么想法吗

    听起来你应该使用特征,而不是枚举。您可以定义一个特征,并按如下方式实现它:

    pub trait ControlItem {
        fn name(&self) -> &str;
    }
    
    struct A(&'static str);
    
    impl ControlItem for A {
        fn name(&self) -> &str {
            self.0
        }
    }
    
    // ... similar struct and impl blocks for other items
    
    然后,这些结构可以移动到单独的板条箱中

    您需要更改
    控件
    以存储
    Vec
    ,或者更改
    获取
    设置
    以获取一个
    ,或者更改
    T:ControlItem
    的通用性


    阅读和了解更多信息。

    我希望有一组预定义的
    控制项
    ,并且不允许在
    集合
    获取
    中有任何其他项,如果没有这个限制,我可以使用
    String
    而不是
    ControlItem
    。但是您之前说过要打开它,以便不同的
    ControlItem
    可以放在不同的板条箱中。是的,它应该放在不同的板条箱中,但它应该是
    open
    ,只能在编译时打开。可能的
    控制项集
    应该在编译时固定,并且
    Set
    get
    应该只接受它们。