Denis Defreyne

Calling by value or reference

Signature for a method that takes a value:
fn length(self) -> Float64

Signature for a method that takes a reference:
fn zero(&self)

Calling a method on a value:
c.length();

Calling a method on a reference:
&c.zero();

I rather like the idea of needing an explicit reference (e.g., &c.zero() rather than c.zero()). This makes it clear at the call site what the effects can/will be.

Full example:

struct Complex {
  real: Float64,
  imag: Float64,

  fn length(self) -> Float64 {
    // …
  }

  fn zero(&self) {
    self.real = 0.0;
    self.imag = 0.0;
  }
}

fn main() {
  var c: Complex = Complex { real=5.0, imag=7.0 };
  println_float64(c.length());
  // 8.60

  &c.zero();
  println_float64(c.length());
  // 0.00
}
Note last edited July 2022.
***