typestar

Structs in Elixir

defstruct gives the kayak shop a fixed shape with defaults and checked keys.

defmodule Kayak do
  # A struct is a map with a fixed field list and compile-time checks.
  defstruct model: "Petrel", length_ft: 17, rudder: false
end

defmodule Boathouse do
  def tour do
    stock = %Kayak{}
    custom = %Kayak{model: "Auk", rudder: true}

    IO.puts("stock build: #{stock.model}, #{stock.length_ft} ft")
    IO.puts("custom build: #{custom.model}, rudder? #{custom.rudder}")

    %Kayak{model: m} = custom
    IO.puts("matched model #{m}")
  end
end

Boathouse.tour()

How it works

  1. defstruct lists the fields and their defaults; the struct lives in its module.
  2. %Kayak{} takes every default; %Kayak{model: "Auk"} overrides fields at build time.
  3. %Kayak{model: m} = custom pattern matches like a map that knows its type.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
457
Tokens
112
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 96 seconds.

Type this snippet

Step 3 of 3 in Maps & structs, step 12 of 27 in Language basics.

← Previous Next →

Structs in other languages