Learn · 08
Structs & Enums
Model domain data with structs, attach methods with impl blocks, and define algebraic tagged enums with data payloads.
Good domain modeling makes illegal states unrepresentable. Ochre provides structs (named product types with impl methods) and tagged enums (sum types whose variants can carry typed data payloads).
Structs & impl Methods
Define a struct with struct Name { field: Type, ... }. Every field must be provided when constructing a struct literal. Attach methods using impl Name { fn method(self, ...) ... }:
struct Rect {
width: Int,
height: Int,
}
impl Rect {
fn area(self) -> Int {
return self.width * self.height
}
fn is_square(self) -> Bool {
return self.width == self.height
}
}
fn main() {
let r = Rect { width: 8, height: 5 }
let sq = Rect { width: 6, height: 6 }
println("area={r.area()}, square={r.is_square()}")
println("sq area={sq.area()}, square={sq.is_square()}")
}
Expected Output
area=40, square=false
sq area=36, square=true
Mutable Struct Fields (var)
Just like collections, mutating a struct field requires the owning variable to be declared with var — and uses Copy-on-Write so snapshots remain unchanged:
struct Counter {
label: Str,
count: Int,
}
fn main() {
var c = Counter { label: "hits", count: 0 }
let start = c
c.count += 5
println("now={c.count}, start={start.count}")
}
Expected Output
now=5, start=0
Tagged Enums with Payloads
An enum represents a closed set of variants. Variants can be unit-like (Pending) or carry typed fields (Paid(Int), Failed(Str)):
enum Payment {
Pending,
Paid(Int),
Failed(Str),
}
fn describe(p: Payment) -> Str {
return match p {
Payment.Pending => "awaiting confirmation",
Payment.Paid(cents) => "paid {cents} cents",
Payment.Failed(reason) => "failed: {reason}",
}
}
fn main() {
println(describe(Payment.Pending))
println(describe(Payment.Paid(4900)))
println(describe(Payment.Failed("card declined")))
}
Expected Output
awaiting confirmation
paid 4900 cents
failed: card declined
Common Mistake: Missing a Struct Field
struct User {
name: Str,
age: Int,
}
fn main() {
let u = User { name: "Ada" }
}
The compiler reports: missing field 'age' in struct 'User'.
Practical Use Case: State Machines
Tagged enums are ideal for job states, HTTP routing outcomes, AST nodes, and CLI commands — because every state carries only the data that is valid in that state.
Exercise
Define an enum Shape with variants Circle(Float) and Rect(Float, Float). Write a function area(s: Shape) -> Float (use 3.14159 for pi) and print the areas of both shapes.
Show Solution
enum Shape {
Circle(Float),
Rect(Float, Float),
}
fn area(s: Shape) -> Float {
return match s {
Shape.Circle(r) => 3.14159 * r * r,
Shape.Rect(w, h) => w * h,
}
}
fn main() {
println(area(Shape.Circle(3.0)))
println(area(Shape.Rect(4.0, 5.0)))
}