Checked views

&value lends read-only access, while &mut value lends exclusive access to a mutable value. The corresponding parameter types are &T and &mut T. The compiler checks that a view is used only while its storage is valid.

A view does not keep a local alive after its scope ends. These checks also apply when a view is passed through a helper or stored in another value. Raw foreign pointers are a separate type family and prove no ownership or lifetime.

This example checks a mutation through a view without calling a native library.

struct Counter { value: int }

fn add(counter: &mut Counter, amount: int) {
  counter.value += amount
}

fn main() {
  let mut counter = Counter { value: 1 }
  add(&mut counter, 2)
}
Run locally
moon check main.mn
Ctrl/⌘+Enter checks the current lesson.