Skip to content
Structs
step 1/5

Reading — step 1 of 5

Learn

~1 min readStructs and Processes

A struct is a Map with a fixed shape. Defined with defstruct inside a module:

defmodule User do
    defstruct [:name, :age, active: true]
end

u = %User{name: "Ada", age: 36}
u.name        # "Ada"
u.active      # true (default)

updated = %{u | age: 37}    # update syntax — returns new struct

The [:name, :age] part lists fields with no default; active: true provides a default.

Pattern matching on structs:

def greet(%User{name: name, age: age}) do
    "Hi, #{name}, age #{age}"
end

The %User{...} part requires the value to be a User struct (not just any map with those keys). This gives you type-tag-like discrimination.

Optional but recommended typespecs:

defmodule User do
    @type t :: %__MODULE__{
        name: String.t(),
        age: non_neg_integer(),
        active: boolean()
    }
    defstruct [:name, :age, active: true]
end

The @type t is a convention for the "main type" exposed by the module. Tools like Dialyzer use these for static analysis.

@enforce_keys makes some fields mandatory:

defmodule User do
    @enforce_keys [:name]
    defstruct [:name, :age, active: true]
end

%User{age: 30}     # ArgumentError — missing :name

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…