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.

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 {
name: String,
age: Integer
}
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}
}

A plain record is not a struct:

pub fn as_user(user: %{name: String, age: Integer}) -> structs.user.User {
user
}

For existing Elixir structs, extern struct gives Gale a type for the native value and its declared fields. See the Externs chapter for functions, foreign types, exceptions, and native modules too.