Records
Records
Records in Gleam are custom types with a single variant that has labeled fields:
pub type Person {
Person(name: String, age: Int)
}
The type name and constructor name are the same. You create a record by calling the constructor:
let alice = Person(name: "Alice", age: 30)
Accessing Fields
You can access fields with dot notation:
alice.name // "Alice"
alice.age // 30
Updating Records
Since all data is immutable, you create new records with updated fields using the spread syntax:
let older_alice = Person(..alice, age: alice.age + 1)
The ..alice copies all fields from alice, then age: alice.age + 1 overrides the age.
Pattern Matching on Records
You can destructure records in case expressions and let bindings:
let Person(name: name, age: age) = alice
// name = "Alice", age = 30
case person {
Person(name: "Admin", ..) -> "admin user"
Person(name: name, age: age) if age >= 18 -> name <> " is an adult"
Person(name: name, ..) -> name <> " is a minor"
}
Records with Multiple Variants
A custom type can have multiple variants, each with their own fields:
pub type Animal {
Dog(name: String, breed: String)
Cat(name: String, indoor: Bool)
Fish(name: String, species: String)
}
Your Task
Define a Rectangle record type with width and height fields (both Int). Write a function area that calculates the area, and a function describe that returns a string in the format "<width>x<height> (area: <area>)". Print descriptions for two rectangles.