Defining structs
To define a struct, the defstruct
construct is used:
iex> defmodule User do
...> defstruct name: "John", age: 27
...> end
The keyword list used with defstruct
defines what fields the struct will have along with their default values.
Structs take the name of the module they’re defined in. In the example above, we defined a struct named User
.
We can now create User
structs by using a syntax similar to the one used to create maps:
iex> %User{}
%User{age: 27, name: "John"}
iex> %User{name: "Meg"}
%User{age: 27, name: "Meg"}
Structs provide compile-time guarantees that only the fields (and all of them) defined through defstruct
will be allowed to exist in a struct:
iex> %User{oops: :field}
** (CompileError) iex:3: unknown key :oops for struct User