Map with statically known keys?
I have a piece of code that I can write in two different ways:
// 1 - Using `match`
struct Processor {
xData: Data,
yData: Data,
zData: Data
}
impl Processor {
fn process(&self, axis: Axis) {
doStuff(match axis {
Axis::X => &self.xData,
Axis::Y => &self.yData,
Axis::Z => &self.zData,
});
}
}
// 2 - Using `HashMap`
struct Processor {
data: HashMap<Axis, Data>
}
impl Processor {
fn process(&self, axis: Axis) {
doStuff(&data[axis])
}
}
This code runs a few million times per second, so it's performance-critical. This is also a simplified example, the actual code handles a few more axes.
The first approach is as fast as it gets, but requires me to manually map enum variants to fields of the struct. So there is a possibility of mistyping one of them, like Axis::Y => &self.xData.
The second approach is as convenient as it gets, but incurs a runtime cost of allocating a HashMap and looking up its values.
Is there a way to combine the upsides of two approaches without using macros, so that the "mapping" of axes to fields happens automatically, and there is no extra runtime cost to it?
I'm not opposed to macros, but it's cheating a bit overkill for my use case. Also, I think my first example is fine as is, I'm just curious if there are other approaches.
Thanks!