Records
Product types, field access, construction, invariants, mutation, generics, and methods.
Contents
A record is a product type with named fields. It is the main way to model a domain object, and it is where Haze's type invariants do most of their work. Records are nominal: the name of the type is part of its identity, so two records with the same fields are not interchangeable.
Declaring a Record#
A record declaration lists its fields with a type after each name. Commas between fields are optional. The formatter aligns the types when the alignment is modest and otherwise leaves a single space.
type Point {
x i32
y i32
}
type Account {
id i32
balance i64
}
A record may be generic. Type parameters are declared after the type name and used in field types.
type Pair[A, B] {
first A
second B
}
type Box[T] {
value T
}
Records may not inherit from other records and there is no structural subtyping. Reuse comes from composition, generics, and traits.
Constructing a Record#
A record literal names each field and gives it a value. All fields are required, duplicates are rejected, and the order of the fields does not matter. A trailing comma is accepted.
const origin = Point { x = 0, y = 0 }
const account = Account { balance = 100, id = 1 }
A generic record is instantiated in the type position and in the literal. The type arguments must be written explicitly; a bare Box { value = 1 } is rejected because Box requires an argument.
const pair = Pair[i32, str] { first = 1, second = "one" }
const box = Box[i32] { value = 10 }
A record value is allocated on the Haze heap and is managed by the collector. Assigning a record to another binding copies the reference, not the fields.
Field Access#
Fields are read with ., and the result has the field's declared type.
fn distance_squared(a Point, b Point) i32 {
const dx = a.x - b.x
const dy = a.y - b.y
return dx * dx + dy * dy
}
There is no record destructuring pattern and no structural equality operator. To compare two records, compare their fields or implement a trait method such as Eq. To transform a record, construct a new one with the fields you want to change.
fn moved(point Point, dx i32, dy i32) Point =>
Point { x = point.x + dx, y = point.y + dy }
Record Invariants#
A record may declare invariants between its fields. The invariant appears after the type name and before the opening brace. Multiple invariants may be written as repeated : invariant clauses. Inside a record invariant, the field names are in scope directly; self is not introduced for records.
pure fn ordered(lo i32, hi i32) bool => lo <= hi
type Window : invariant ordered(lo, hi) {
lo i32
hi i32
}
An invariant must be a boolean expression, and it may call only pure functions. It may also refer to module constants and other pure helpers. The invariant is checked when a value is constructed, not continuously afterwards. A record with an invariant cannot have one field assigned in isolation, because the write could break the relationship between fields.
type Range : invariant lo <= hi {
lo i32
hi i32
}
fn widen(range Range, by i32) Result[Range, str] {
const lo = range.lo - by
const hi = range.hi + by
return Success(Range { lo = lo, hi = hi }?)
}
The checked construction Range { ... }? is required because the new bounds are runtime values. If the new bounds violate lo <= hi, the construction returns Error("invariant failed for 'Range'") from a function whose return type is a compatible Result. The Checked Construction chapter gives the full rule.
Normal Construction and Constant Checking#
A normal record construction has type T and must never fail. It is therefore accepted only when every field value is a compile-time constant that satisfies the invariants, or when the value already has the target type. A constant that provably violates an invariant is a compile error.
type Positive = i32 : invariant self > 0
type Pair : invariant x == y && y > 10 {
x Positive
y Positive
}
const good = Pair { x = 12, y = 12 } // checked at compile time
// const bad = Pair { x = 5, y = 5 } // error: y > 10 fails
When a field value is a runtime value, use checked construction in a Result-returning function.
fn build_pair(n i32) Result[Pair, str] {
const x = Positive { n }?
const y = Positive { n }?
return Success(Pair { x = x, y = y }?)
}
Mutation#
A record field may be assigned when the binding is a var, the record has no own invariants, and the assignment does not violate a field's refinement type. Assigning through a const binding is rejected, as is assigning a single field of a record that has a cross-field invariant.
type Counter {
n i32
}
fn bump(counter Counter) {
counter.n += 1
}
fn main() {
var counter = Counter { n = 1 }
bump(counter)
print(counter.n) // 2
}
The bump function mutates the caller's record because the parameter is a reference to the same managed object. This is sometimes appropriate for a small, local helper, but public APIs should usually return a new record so that the caller can see the value transition.
Methods#
A record has no method declarations inside its body. Methods are free functions whose first parameter is the record, called with method syntax, or trait methods implemented for the record.
fn area(rect Rect) f64 => rect.width * rect.height
fn main() {
const rect = Rect { width = 3.0, height = 4.0 }
print(rect.area())
}
A trait implementation provides a named set of methods for a record. The implementation is separate from the type declaration, which allows the entry module to implement a trait for a type imported from another module.
trait Describable {
fn describe(self Self) str
}
impl Account of Describable {
fn describe(self Account) str => $"account {self.id}: {self.balance}"
}
The Traits chapter covers method resolution, default methods, and bounds.
Aliasing and Const#
Because records are references, a const binding prevents assignment through that binding but does not make the object deeply immutable if another mutable reference exists. In ordinary code, treat a record as immutable unless its API says otherwise, and prefer constructing a replacement value.
var first = Point { x = 1, y = 2 }
var second = first
second.x = 9
print(first.x) // 9: both bindings refer to the same record
If a record is intended to be a value object, keep it small, avoid sharing mutable references to it, and return new records for updates. This is both easier to reason about and closer to the collector's preferred publication pattern.
Records in Contracts#
Record fields are ordinary expressions, so contracts can describe relationships between fields.
pure fn solvent(account Account) bool =>
account.balance >= 0 && account.balance <= MAX_BALANCE
fn deposit(account Account, amount i64) Account
: pre amount > 0
: post r => r.id == account.id
: post r => r.balance == account.balance + amount
=> Account { id = account.id, balance = account.balance + amount }
Postconditions see the current values of parameters. Haze has no old expression, so if a function mutates a parameter, a postcondition that refers to that parameter sees the mutated value, not the pre-state. The idiomatic rule is to avoid mutating parameters in functions whose contracts describe a transition.
Summary#
| Feature | Rule |
|---|---|
| Declaration | type Name { field Type ... } |
| Construction | Name { field = value, ... }, all fields required |
| Generics | type Name[T] { ... }, construct as Name[T] { ... } |
| Field access | value.field |
| Field assignment | Only through var, and only when the record has no own invariants |
| Invariants | type Name : invariant expr { ... }, fields in scope |
| Methods | Free functions or trait implementations |
| Equality | No structural ==; use fields or a trait |
| Patterns | No record patterns; use field access |
| Memory | Managed reference |