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
应该只接受它们。