Removing match duplication


#1

Hey all,

So, I’ve been toying around with some code this evening, and while it works, I think I can make it better. I was about to give it a shot, but thought I’d also ask what you all thought.

The code in question looks like this: https://github.com/steveklabnik/grok/blob/1c1544ce0fe78aed4752c377dfe695c3fb934c64/src/main.rs#L28-L50

What I’m doing here is mapping an enum to a member of a struct. This is nice for type safety reasons, but is really annoying for duplication reasons.

How would you clean up code like this?


#2

If you change Operation to something like:

struct Operation {
    register: Register,
    action: Action
}
enum Action {
    Set(u64), Increment, Decrement,
}

Then the matchs can be written separately naturally:

let reg = match operation.register {
    Register::A => &mut registers.a,
    Register::B => &mut registers.b,
    Register::C => &mut registers.c,
};
match operation.action {
    Action::Set(val) => *reg = val,
    Action::Increment => *reg += 1,
    Action::Decrement => *reg -= 1,
}