Mutable References

Values in pyr are immutable by default. To let a function modify a struct's fields, the parameter must be declared as *mut and the caller must pass &mut explicitly. This makes mutation visible at every call site.

Function parameters are immutable by default. Field assignment on a non-*mut param is a compile error.

struct Point {
  x: int
  y: int
}

*mut T declares that a function mutates the argument.

fn translate(p: *mut Point, dx: int, dy: int) {
  p.x += dx
  p.y += dy
}

Read-only access needs no special syntax.

fn magnitude(p: Point) -> int {
  p.x + p.y
}

At the call site, &mut makes mutation visible. The variable must be declared mut.

fn main() {
  mut p = Point { x: 1, y: 2 }
  println(magnitude(p))

  translate(&mut p, 10, 20)
  println(p.x)
  println(p.y)
}
$ pyr run pointers.pyr
3
11
22