Kembali ke Perpustakaan
Region:
Switch to EN
Menengah Exercism • elixir
Structs
Ringkasan Pelajaran
# Introduction
About
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
defstructconstruct.- The construct usually immediately follows after the module definition.
defstructaccepts 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.
- The Access Behaviour is an exception and is not implemented for 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_keysmodule attribute creates a run-time check that specified fields must be initialized to a non-nilvalue when the struct is created. @enforce_keysis 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]
Originally from Exercism elixir concepts