Structs are special maps with a defined set of keys.
defstruct
construct.
defstruct
accepts either a list of atoms (for nil default values) or keyword lists (for specified default values).
defmodule Plane do
defstruct [:engine, wings: 2]
end
plane = %Plane{}
# => %Plane{engine: nil, wings: 2}
Most functions that work with maps will also work with structs.
It is recommended to use the static access operator .
to access struct fields.
Get/fetch field values:
plane = %Plane{}
plane.engine
# => nil
Map.fetch(plane, :wings)
# => {:ok, 2}
Update field values
plane = %Plane{}
%{plane | wings: 4}
# => %Plane{engine: nil, wings: 4}
@enforce_keys
module attribute creates a run-time check that specified fields must be initialized to a non-nil
value when the struct is created.@enforce_keys
is followed by a list of the field keys (which are atoms).defmodule User do
@enforce_keys [:username]
defstruct [:username]
end
%User{}
# => (ArgumentError) the following keys must also be given when building struct User: [:username]