Ship

Book · Mutability

Mutability

Draft

Assign mut places with :=, or bind a new name with let.

On this page · 3 sections

Mutable locals

Values are immutable by default. let mut makes a binding assignable. := writes it and yields the right-hand side. Record fields use the same spelling in updating records.

Mutable Locals

test✓
  let mut countcount: Int = 00: Int;
  let nextnext: Int = count := countcount: Int + 11: Int;
  expect ✓(nextnext: Int, countcount: Int) == (11: Int, 11: Int);

Shadowing

let again binds a new name. That is not :=. Shadowing is local: a module cannot define the same value or type twice.

Shadowing

test✓
  let countcount: Int = 00: Int;
  let countcount: Int = countcount: Int + 11: Int;
  if TrueTrue: Bool {
    let countcount: Int = countcount: Int + 11: Int;
    expect ✓countcount: Int == 22: Int;
  }
  expect ✓countcount: Int == 11: Int;

Nested := writes the outer mut binding.

If Assignment

test✓
  let mut nn: Int = 00: Int;
  if TrueTrue: Bool {
    n := 33: Int;
  }
  expect ✓nn: Int == 33: Int;

Assignment

a := b := 0 is right-associative and writes both.

Chained Assignment

test✓
  let mut aa: Int = 11: Int;
  let mut bb: Int = 22: Int;
  let writtenwritten: Int = a := b := 00: Int;
  expect ✓(writtenwritten: Int, aa: Int, bb: Int) == (00: Int, 00: Int, 00: Int);

A match arm can be an assignment. { ident := ... } is a block, not a record.

Match Arm Assignment

test✓
  let mut scanningscanning: Bool = TrueTrue: Bool;
  match 00: Int {
    | 0 -> scanning := FalseFalse: Bool
    | _ -> scanning := TrueTrue: Bool
  }
  expect ✓scanningscanning: Bool == FalseFalse: Bool;