View Source Structs
A Struct
is an extension of a Map
and is defined inside a Module
. It allows you to define fields at compile-time, require certain fields, set default values, and it raises if you try to set a field that doesn't exist. You can define a struct with defstruct/1
.
defmodule RunElixir.Profile do
# Make the :name field required
@enforce_keys [:name]
defstruct [:name, :age, status: :active] # <- Set the default value of :status to :active
# You can match against the struct like this.
# This function raises if it receives a plain map and not a struct.
def adult?(%RunElixir.Profile{age: age}) do
age >= 18
end
end
You can create a struct like this:
struct = %RunElixir.Profile{name: "Peter", age: 21}
# You can access the struct's fields using the dot-notation
struct.name # => "Peter"
struct.status # => :active
Structs give you some nice checks for free, like an exception if you try to set a field that doesn't exist.
struct = %RunElixir.Profile{height: 190}
** (KeyError) key :height not found
expanding struct: RunElixir.Profile.__struct__/1
Structs can also require fields and raise if they are not set.
struct = %RunElixir.Profile{age: 21}
** (ArgumentError) the following keys must also be given when building struct RunElixir.Profile: [:name]
expanding struct: RunElixir.Profile.__struct__/1