Correct way to invoke struct methods with self

Hello,

during my implementation of struct for one of advent of code tasks I have encountered for following error:

> error[E0061]: this function takes 3 parameters but 2 parameters were supplied
>   --> src/Computer.rs:71:44
>    |
> 65 |   fn add(&self, num_1_pos: usize, num_2_pos: usize) -> i32 { self.intcode.get_value_from_pos(num_1_pos) + self.intcode.get_value_from_pos(num_2_pos) }
>    |   -------------------------------------------------------- defined here
> ...
> 71 |         1 => self.intcode.set_value_at_pos(Self::add(num_1_pos as usize, num_2_pos as usize), target_pos as usize),
>    |                                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected 3 parameters

Error occured for following struct implementation:

impl Computer {
  pub fn init_with_intcode(intcode: Intcode) -> Computer {
    Computer {
      intcode: intcode,
    }
  }

  fn add(&self, num_1_pos: usize, num_2_pos: usize) -> i32 { self.intcode.get_value_from_pos(num_1_pos) + self.intcode.get_value_from_pos(num_2_pos) }
  fn multiply(&self, num_1_pos: usize, num_2_pos: usize) -> i32 { self.intcode.get_value_from_pos(num_1_pos) * self.intcode.get_value_from_pos(num_2_pos) }

  pub fn calculate(&mut self) -> Option<&mut Intcode> {
    while let Some((opcode, num_1_pos, num_2_pos, target_pos)) = self.intcode.next() {
      match opcode {
        1 => self.intcode.set_value_at_pos(Self::add(num_1_pos as usize, num_2_pos as usize), target_pos as usize),
        2 => self.intcode.set_value_at_pos(Self::multiply(num_1_pos as usize, num_2_pos as usize), target_pos as usize),
        99 => { 
          println!("Encountered opcode of 99. Finishing computations...");
          break;
        }
        _ => { panic!("Unexpected opcode value"); }
      }
    }
    Some(&mut self.intcode)
  }
}

Problem seems to be that '&self' in both add and multiply functions definitions seems to be treated as 'normal' parameter and therefore i have to provide 'self' as first parameter during invocation to make it work.

Could anyone please tell me why does it happen? I don't understand why both functions interpret '&self' like that and force me to pass it during invocation?

Regards!

What you want is self.add(num_1_pos as usize, num_2_pos as usize). This is method syntax, and is what the (&self style functions are getting you.

If you don't want to use method syntax for some reason, you need to provide that parameter explicitly: Self::add(self, num_1_pos as usize, num_2_pos as usize).

Thank you for your answer. It works fine now :slight_smile: Regards

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