Skip to content

Structs

A struct is a named type in its own file. The struct block follows the mod header. Ordinary functions follow the block. A struct is not a record. Copy fields explicitly to convert between them.

User is a named type with declared fields. It remains distinct from a record with the same fields and from other struct types. Construction and updates must use its declared fields.

A struct lives in its own module: struct User { ... } explicitly names its Gale type, and emits into the enclosing Elixir module. The name conventionally matches the module but can differ. Each module owns at most one struct or exception. Functions follow the declaration. Fields may declare pure defaults, used whenever construction omits them:

mod structs.user
@moduledoc """
A struct is a named type in its own file. The `struct` block follows the
mod header. Ordinary functions follow the block. A struct is not a record.
Copy fields explicitly to convert between them.
"""
struct User {
name: String,
age: Integer = 0
}
pub fn new(name: String) -> User {
%User{name: name}
}
pub fn ada() -> User {
%User{name: "Ada", age: 36}
}
pub fn birthday(user: User) -> User {
%{user | age: user.age + 1}
}
pub fn as_record(user: User) -> %{name: String, age: Integer} {
%{name: user.name, age: user.age}
}

new("Ada") has age zero. Defaults must be pure. Use a factory function for initialization with effects.

The two types stay separate even with identical fields. The as_record function above converts by copying each field explicitly.

The compiler rejects implicit conversion in both directions.

For existing Elixir structs, extern struct gives Gale a type for the native value and its fields; see the externs chapter for functions, foreign types, exceptions and native modules.

Structs take type parameters like any other declaration. Box<A> keeps the payload’s type while staying a named struct:

A struct may have type parameters. Box<A> keeps the payload’s type while remaining a named struct, distinct from a record with a value field.

mod structs.box
@moduledoc """
A struct may have type parameters. `Box<A>` keeps the payload's type while
remaining a named struct, distinct from a record with a value field.
"""
struct Box<A> {
value: A
}
pub fn new<A>(value: A) -> Box<A> {
%Box{value: value}
}
pub fn map<A, B>(box: Box<A>, transform: fn(A) -> B) -> Box<B> {
%Box{value: transform.(box.value)}
}

An exception uses the same construction, field access, updates, and patterns as a struct, and adds Elixir’s native exception interface. The exceptions chapter covers declaration, matching, and interop.