I have a Struct which contains just one Vector. I'm using an enum to index and get values of this vector.
Here is the code up till now (It does't compile) :
use std::ops::Index;
enum reg {
pc = 0,
cnt = 1,
}
struct Reg {
reg: Vec<u16>,
}
impl Index<reg> for Reg {
type Output = u16; // doubt
fn index(&self, rg: reg) -> &Self::Output {
match rg {
rg::pc => &self.reg[0];
rg::cnt => &self.reg[1];
}
}
}
fn main() {
let a = Reg{ reg: vec![0u16;5] };
println!("{}", a[reg::pc]);
}
As you can see, I'm stuck at how exactly I should be implementing the Index trait, especially what should I be having as the Output type here? (Note: I'm completely new to Rust )
PC: My main intention is to use an enum to index through a vector. I didn't want to type myvec[myenum::a as usize]
everytime, and I was looking for different ways of achieving this.
EDIT: I should have added that I'm looking for a way to use an enum to index over a mutable vector. That is I would like to do something like:
a[reg::pc] = 2;