hanki

12. Mutability and visibility

x = 5         # immutable
var y = 0     # mutable
y = y + 1     # OK
struct Point
  x: i32
  y: i32
end

def main!() -> () [Crash]
  var p = Point(x=1i32, y=2i32)
  q = p             # copy of the binding
  p.x = 9i32        # rebinds p; q is untouched
  assert!(p.x == 9i32)   # p sees its own update
  assert!(q.x == 1i32)   # q keeps the old value - no aliasing
end
open option

struct Node
  id: i64
  next: Option<Node>
end

# Total: values are acyclic, so the chain always ends.
def len(n: Node) -> i64
  match n.next
    Some(rest) -> 1i64 + len(rest)
    None -> 0i64
  end
end

def main!() -> () [Crash]
  var x = Node(id=1i64, next=None)
  y = Node(id=2i64, next=Some(x))   # y.next holds x's value
  x.next = Some(y)                  # rebinds x - ties no knot
  assert!(len(x) == 2i64)           # x -> y -> old x; the chain ends
end