Structs
Understand how structs work in Elixir.
We'll cover the following
Why do we need structs?
When Elixir sees %{ ... }
, it knows it’s looking at a map. But it doesn’t know much more than that. In particular, it doesn’t know what we intend to do with the map, whether only certain keys are allowed, or whether some keys should have default values. That’s fine for anonymous maps. But what if we want to create a typed map? A typed map has a fixed set of fields and default values for those fields, and we can pattern match by type as well as content.
A struct is just a module that wraps a limited form of a map. It’s limited because the keys must be atoms, and these maps don’t have dictionary capabilities. The name of the module becomes the name of the map type. Inside the module, we use the defstruct
macro to define the struct’s members.
Note: The syntax for creating a struct is the same as the syntax for creating a map. We simply add the module name between
%
and{}
.
Get hands-on with 1400+ tech skills courses.