St

Structs in Elixir

18 exercises

About Structs

Structs are special maps with a defined set of keys.

  • Structs provide compile-time checks and default values.
  • A struct is named after the module it is defined in.
  • To define a struct use the defstruct construct.
    • The construct usually immediately follows after the module definition.
  • defstruct accepts either a list of atoms (for nil default values) or keyword lists (for specified default values).
    • The fields without defaults must precede the fields with default values.
defmodule Plane do
  defstruct [:engine, wings: 2]
end

plane = %Plane{}
# => %Plane{engine: nil, wings: 2}

Accessing fields and updating

  • 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}
    

Enforcing field value initialization

  • The @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).
  • If an enforced key is not initialized, an error is raised.
defmodule User do
  @enforce_keys [:username]
  defstruct [:username]
end

%User{}
# => (ArgumentError) the following keys must also be given when building struct User: [:username]
Edit via GitHub The link opens in a new window or tab

Learn Structs

Practicing is locked

Unlock 7 more exercises to practice Structs