Struct
A struct is a map variant that includes compile-time checks and default values. The defstruct construct is used to define a struct:
iex> defmodule Product do (1)
...> defstruct name: nil, price: 0 (2)
...> end
iex> %Product{}
%Product{name: nil, price: 0}
iex> apple = %Product{name: "Apple", price: 0.5} (3)
%Product{name: "Apple", price: 0.5}
iex> apple
%Product{name: "Apple", price: 0.5}
iex> apple.price
0.5
iex> orange = %Product{name: "Orange"} (4)
%Product{name: "Orange", price: 0}
| 1 | Here we define a new struct named Product with the keys name and price. |
| 2 | Default values are set for the keys. |
| 3 | A new Product struct is created, setting values for all keys. |
| 4 | A new Product struct is created with only the name set, leaving the price at its default value. |
Structs ensure that only defined fields can be accessed:
iex> apple.description (1)
** (KeyError) key :description not found in:
%Product{name: "Apple", price: 0.5}
iex> banana = %Product{name: "Banana", weight: 0.1} (2)
** (KeyError) key :weight not found
expanding struct: Product.__struct__/1
iex:7: (file)
iex>
| 1 | Accessing an undefined field, like description in the Product struct, will result in an error. |
| 2 | Similarly, trying to set an undefined field, such as weight, while creating a new struct will also cause an error. |
| As structs are built on top of maps, all map functions are applicable to them. |