Structs and enums
Structs
Section titled “Structs”struct Point { x: int, y: int }
p := Point{ x: 1, y: 2 }p.x = 10Nested mutation works: rect.origin.x = 9.
Embedding
Section titled “Embedding”Name a type without a field to embed it. Fields and methods promote transitively; direct members win:
struct Base { id: int, name: str }struct User { Base, age: int }
impl Base { func area(self) -> int { self.id * 2 }}
u := User{ id: 1, name: "Ada", age: 36 }u.id // 1, same as u.Base.idu.area() // 2u.id = 99 // writes through to u.Base.idUser{ id: 1, ... }, User{ Base: Base{...}, ... }, and
User{ Base{...}, ... } mean the same. Mixing explicit + flattened leaves
of one subtree is ambiguous and rejected.
Generic structs
Section titled “Generic structs”struct Box<T> { v: T }
impl Box<T> { func get(self) -> T { self.v }}
b := Box{ v: 42 } // Box<int>, inferredRules: use sites name args (Box<int>, never bare Box).
Box<int> vs Box<str> are distinct types. impl Box<T> scopes T over
methods. Args erase at runtime.
Type aliases
Section titled “Type aliases”enum Token { Eof, IntLit(int), Name(str) }
type Tokens = [Token]type Pair<T> = (T, T)
toks: Tokens = [Token.Eof]p: Pair<int> = (1, 2)Erase at check time, zero runtime cost. pub type exports across modules.
enum Token { Eof, IntLit(int), Name(str),}
t := Token.IntLit(42)match t { .Eof => "eof", .IntLit(v) => "int", .Name(s) => s,}- Construction is qualified (
Token.IntLit(42)); patterns are short (.IntLit(v)). - Matches are exhaustiveness-checked; add
_or cover every variant. - One payload max per variant — use a tuple for more.
- Generic (
enum Box<T> { V(T), E }), methods (impl Token),if let, nesting, and structural equality all work.pub enumexports.
Method dispatch
Section titled “Method dispatch”value.name(...) resolves in this order:
- the receiver’s own
implmethod —impl W { func get(self) }registersW.get, andw.get()reaches it even when a freeget(w)exists; - a free function
namewith the receiver as its first argument (p.dist()isdist(p)), when the receiver’s type has no such method; - the receiver-typed stdlib namespace (
str.,vec.,dict.,option.).
Both forms stay reachable, so a same-named pair can coexist:
struct W { v: int }func get(w: W) -> str { "free" }impl W { func get(self) -> str { "method" }}
w := W{ v: 1 }w.get() // "method"get(w) // "free"Keep the names distinct when the semantics differ — a method call always prefers the method, never the free function.
Recursive types
Section titled “Recursive types”Behind an indirection (array, Option, dict) plus mutual pairs:
struct Node { n: int, kids: [Node] }enum R { Null, Int(int), List([R]) }Order never matters. Every bind deep-copies, so depth-n builds by wrapping cost O(n²) until move semantics land. Keep depth modest; prefer iteration for large inputs. Very deep values abort with stack-overflow, never silent corruption.
Printing renders Type{field: value, ...} identically on VM and AOT.