Store struct function pointers inside self array

Hi, I'm new to rust and I am trying to write a CPU simulator.

I have something like this:

struct CPU {
    reg_a: u8,
    reg_b: u8,
    reg_r: u8,
impl CPU {
    fn add_ab(&mut self) {
        self.reg_r = self.reg_a + self.reg_b;
    fn sub_ab(&mut self) {
        self.reg_r = self.reg_a - self.reg_b;

I would like to have an array of function pointers in CPU in order to have a method like this in CPU implementation:

    fn exec(&mut self, instruction_index : u16){

And call the CPU intance this way: cpu.exec(7)

I don't know if I can reference non-static methods inside the struct itself.

Thanks in advance.

I would pass the CPU object as a parameter when calling your instruction functions, and I would store the instruction array outside the CPU object as you otherwise cannot pass it a mutable reference to the CPU.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.