How to split a jumper in two in different drawers?

Here's where I start with:

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

      

I have a type Control

that should save the state of some predefined elements and report it to the user.

I have a virtual table in my head like:

|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|

      

  • I want to Control

    have methods get

    / set

    that only accept things with names item_1

    , item_2

    , item_3

    .

  • I want to host this virtual table in two boxes: "main" and "platform". Most of the implementation Control

    should be in the main box, and element definitions (for example item_3

    ) should go to the platform box. I want to register item_3

    at compile time.

Any ideas on how to achieve this?

+2


source to share


1 answer


It sounds like you should be using a trait and not an enum. You can define a trait and implement it like this:

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

      

These structures can then be moved to separate boxes.



You need to change Control

to save Vec<(Box<ControlItem>, bool)>

, and either change get

and set

to take Box<ControlItem>

, or be shared by T: ControlItem

.

Read traits and object objects for more.

0


source







All Articles