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
defstructlists the fields and their defaults; the struct lives in its module.%Kayak{}takes every default;%Kayak{model: "Auk"}overrides fields at build time.%Kayak{model: m} = custompattern matches like a map that knows its type.
Keywords and builtins used here
BoathouseIOKayakdefdefmoduledefstructdoend
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.
Step 3 of 3 in Maps & structs, step 12 of 27 in Language basics.