2016-08-15 59 views
2

这里就是我从开始:如何在不同的包装箱中将枚举拆分为两部分?

#[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); 
} 

我有一个Control类型应该保存的一些预定义项的状态,并报告回给用户。

我有一个虚拟表在我脑海中,像这样:

|Name in program | Name for user    | 
|item_1   | Item one bla-bla   | 
|item_2   | Item two bla-bla   | 
|item_3   | Item three another-bla-bla| 
  1. 我想Controlget/set方法只接受与名称item_1item_2item_3事情。

  2. 我想在两个箱子里放置这个虚拟表格:“main”和“platform”。 Control的大部分实现应该放在主箱中,并且项目的定义(如item_3)应该放入平台箱中。我想在编译时注册item_3

有关如何实现此目的的任何想法?

回答

0

这听起来像你应该使用一个特质,而不是一个枚举。你可以定义一个特质,并像这样实现它:

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 

然后这些结构可以移动到单独的箱子中。

你需要改变Control来存储Vec<(Box<ControlItem>, bool)>,并要么改变getset采取Box<ControlItem>,或在T: ControlItem是通用的。

阅读更多关于traitstrait objects

+0

用'ControlItem'的问题,我想有预定义的ControlItem'的',不允许在'set'和'GET'任何其他没有这个限制,我可以只使用'String',而不是'ControlItem'。 – user1244932

+0

但是你之前说过要打开它,以便不同的ControlItem可以放在不同的包装箱中。 – durka42

+0

是的,它应该是在不同的箱子,但只有在编译的时候应该是'打开up'。组可能'ControlItem'应固定在编译时和'set'和'GET'应该只接受他们。 – user1244932

相关问题