Download

8. Memory Model

GC#

Every value that is not a primitive (a struct, an array, the contents of a string, and the standard library types built from them) is managed by a garbage collector. A program never frees memory: a value stays alive as long as the program can reach it.

GC backends#

Each backend provides the collector. A native binary carries its own, described in docs/RUNTIME.md Memory. On the WebAssembly backend (planned, §17), the WebAssembly host is to collect the values, through the WebAssembly GC proposal.

Storage semantics#

  • Primitives (i32, f64, bool, ...) are values, copied on assignment.
  • A string is an immutable value, copied on assignment. Copies share their content.
  • Structs and arrays live on the heap and are reached through implicit references. A function a struct or an array is passed to reaches the caller's value, and can modify it unless it is frozen (§5 Frozen values).

No visible pointers#

There is no address-of or dereference operator and no pointer type. Memory is managed implicitly. Explicit allocators are planned for performance-critical code (Explicit allocators, below).

Escape analysis#

The compiler may allocate a struct on the stack when it proves that the struct does not escape. It is never required to, and a program cannot observe the difference.

Explicit allocators#

An API is planned to allocate into an arena, a buffer and the like in performance-critical code, alongside the garbage collector. It is not specified yet.

Finalizers#

There are none. A resource other than memory (a file, a socket, a handle) is released explicitly, with defer (§7 defer):

file :: open("a.txt")
defer close(file)