Records & Data

Hale models structured data with nominal type records, tagged enum unions, and type-tagged set unions (A | B | C). Every data type is checked at compile…

Hale models structured data with nominal type records, tagged enum unions, and type-tagged set unions (A | B | C). Every data type is checked at compile time, copied by value with automatic copy-on-write optimization, and matched exhaustively with match.

type Book { id: Int; title: String; }
type Trade { qty: Int; px: Decimal<2>; }
type Inbound = Book | Trade;
fn describe(msg: Inbound) -> String {
return match msg {
Book(b) -> f"book #{b.id}: {b.title}",
Trade(t) -> f"trade {t.qty} @ {t.px}",
};
}
fn main() {
let m: Inbound = Trade { qty: 10, px: 42.50d };
println(describe(m));
}

Data Declarations Overview

Section titled “Data Declarations Overview”
Construct Syntax Example Description
Record (type) type Player { id: String; score: Int = 0; } Fixed-layout product type with optional field defaults
Enum (enum) type Event = enum { Tick(Int), Halt }; Tagged union with unit or payload-carrying variants
Set union (|) type Inbound = Book | Trade | Unknown; Union of existing struct/enum types where the member type is the tag
Type alias type Cents = Int; / type UserId = String; Transparent synonym for an existing type
Fixed array / slice [Int; 8] / [Player] Inline fixed-length array ([0; 8]) or slice view
Tuple let pair = (1, "one"); Lightweight anonymous grouping

Records (type)

Section titled “Records (type)”

Declare a record at the top level of a file with type Name { ... } and construct it with a struct literal:

type Config {
host: String = "127.0.0.1";
port: Int = 8080;
}
fn main() {
let c = Config { port: 9000 }; // `host` uses its default "127.0.0.1"
println(c.host, ":", c.port);
}

Optional Fields (x?: T)

Section titled “Optional Fields (x?: T)”

A field marked ? may be absent. x?: T declares x and, right after it, a real Bool field has_x that says whether x holds a value; x?: T clearable adds clear_x as well, for a PATCH field whose null means “clear it”:

type Ticker {
symbol: String;
last?: Decimal<8>;
expires_at?: Time clearable;
limit?: Int = 100;
}
fn main() {
let mut t = Ticker { symbol: "BTC" }; // `last` left out: absent
println(t.has_last); // false
t.last = 97000.5d; // a write sets the flag
println(t.has_last); // true
println(t.limit, t.has_limit); // 100 false: absent, at its default
}

Value Copy Semantics and Mutation

Section titled “Value Copy Semantics and Mutation”

Independent Value Copies and Copy-on-Write

Section titled “Independent Value Copies and Copy-on-Write”

Binding a record, String, Bytes, tuple, or array from a field or variable (let saved = self.row; or copy = saved;) gives the binding an independent logical copy of the value:

let saved = self.row;
self.row = Row { }; // `saved` retains the previous value
let mut copy = saved;
copy.score = 9; // `saved.score` is unchanged

Under the hood, the compiler avoids copying whenever no mutation can alias the read, and performs a copy on the first write into a local derived from a field, match payload, for element, or tuple.

In-Place Read-Modify-Write Optimization

Section titled “In-Place Read-Modify-Write Optimization”

To update a nested array or field inside a locus, either assign directly (self.row.scores[0] = 9;) or read into a local, mutate, and write it back:

let mut scores = self.row.scores;
scores[0] = 9; // `self.row.scores` is unchanged until written back
self.row.scores = scores; // optimized to an in-place write with zero allocations

When a local read from a field is mutated and written back to the same field with no intervening reads of that field, the compiler updates the field’s storage in place without allocating or copying.

Reference Semantics for Parameters, @form(vec) Iteration, and Locus Handles

Section titled “Reference Semantics for Parameters, @form(vec) Iteration, and Locus Handles”
Target Mutation Behavior
Record function parameter (fn bump(r: Row)) Passed by reference to the caller’s value; r.scores[0] = 9; mutates the caller’s record.
@form(vec) loop variable (for x in v.items) Visits the vec’s cells in place; writing through x updates the stored element.
Locus field via handle (l.name = s;) Copies s into locus l’s arena and recycles the replaced value so repeated external writes never grow l’s arena.

A method that writes into a record parameter (fn put(x: Bag, p: Bytes) { x.b = p; }) writes the caller’s record, so the value is kept as long as that record, never only for the call, whether the method is fallible(E) or not (and when it then fails). The method may pass the record on to another writer, directly or through a block, if or match, and the same holds at every step. A record a field of self holds (put_free(self.bag, p)) is kept in the locus’s arena. One call can hand a writer only one owner’s records. self.put_two(self.held, x, p), or self.put(if c { self.held } else { x }, p), mixes the locus’s record with the caller’s and is rejected. Copy one side into a local record first (let mine = Bag { b: x.b };) and hand that, or write the held record through self.

Such a write is not recycled when the method returns, and does not replace the old value in place the way self.bag.b = p does. Handing a writer self.bag once per message, or once per pass of a run() loop, keeps every value until the locus dissolves, and hale check reports the call as an unbounded allocation. Write the held record through self instead, or hand the writer a record the loop body builds.

Arrays ([T; N]) and Tuples

Section titled “Arrays ([T; N]) and Tuples”

Use [T; N] for fixed-length inline arrays, [T] for slice views, and (a, b) for small ad-hoc tuples:

type Match { players: [Player]; } // slice field
let xs = [1, 2, 3]; // [Int; 3]
let zeros = [0; 8]; // [Int; 8] filled with 0
let pair = (1, "one"); // tuple

For growable lists, use a @form(vec) locus or bounded[T; N] (Lists & Maps).

Type Aliases (type Name = Target;)

Section titled “Type Aliases (type Name = Target;)”

A type alias introduces a transparent synonym for an existing type:

type Cents = Int;
fn price_of(n: Cents) -> Cents { return n * 2; }
fn main() {
let c: Cents = 250;
println(price_of(c));
}

Because Cents is transparent, it is completely interchangeable with Int (including in struct construction RowAlias { id: 1 } and enum patterns LightAlias::Red). If you need the compiler to reject mixing two integer types, use distinct Int (Units, End to End) or a single-field struct (type Cents { v: Int; }).

Type Alias Rules

Section titled “Type Alias Rules”
  1. Literal construction requires a record or locus target: If type Cents = Int;, writing Cents { } is a compile error.
  2. No cyclic aliases: type A = B; type B = A; is rejected.
  3. Concrete generic aliases only: An alias can name one instantiation of a generic record or locus (type OrderReply = Envelope<Order>;), and let r: OrderReply = Envelope { data: o }; then takes its type arguments from the alias. An alias cannot take parameters itself: type Reply<T> = Envelope<T>; is refused.

Enums (enum) and Exhaustive match

Section titled “Enums (enum) and Exhaustive match”

An enum defines a tagged union whose variants may be unit tags or carry positional payloads:

type Event = enum {
Tick(Int),
Trade(Decimal, Int),
Halt,
};
fn handle(e: Event) {
match e {
Event::Tick(0) -> println("tick zero"),
Event::Tick(n) -> println("tick #", n),
Event::Trade(price, size) -> println("trade ", size, " @ ", price),
Event::Halt -> println("halt"),
}
}
fn main() {
handle(Event::Tick(0));
handle(Event::Trade(19.99d, 5));
}

Names, Parsing and the Variant List

Section titled “Names, Parsing and the Variant List”

Don’t write a name function and a parse function for each enum. The compiler writes four for every enum E:

type Lifecycle = enum { Active, Archived };
fn load(status: String) -> Lifecycle {
// an unknown name fails with ParseError { kind: "unknown_variant", input }
return Lifecycle::parse(status) or Lifecycle::Active;
}
fn main() {
for l in Lifecycle::variants { // [Lifecycle; 2], declaration order
println(Lifecycle::index(l), " ", Lifecycle::name(l)); // 0 Active, 1 Archived
}
}

Set Types (A | B | C)

Section titled “Set Types (A | B | C)”

When each alternative is already a standalone type record or enum, declare a set type using | instead of wrapping each record in a redundant enum variant:

type Book { id: Int; title: String; }
type Trade { qty: Int; px: Float; }
type Unknown { raw: String; }
type Inbound = Book | Trade | Unknown;
fn decode(n: Int) -> Inbound {
if n == 0 { return Book { id: 7, title: "Kim" }; }
if n == 1 { return Trade { qty: 2, px: 1.5 }; }
return Unknown { raw: "?" };
}
fn describe(m: Inbound) -> String {
return match m {
Book(b) -> "book " + b.title,
Trade(t) -> "trade of " + to_string(t.qty),
Unknown(u) -> "unknown " + u.raw,
};
}

Generic Records

Section titled “Generic Records”

A record can take type parameters (type Envelope<T> { data: T; request_id: String = ""; }), and so can a locus or a fn. See Generics.

Next: Strings & Bytes.