Structs
When Elixir sees %{ … } it knows it is looking at a map. But it doesn’t know much more than that. In particular, it doesn’t know what you 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 map that has a fixed set of fields and default values for those fields, and that you can pattern-match by type as well as content.
Enter the struct.
A struct is just a module that wraps a limited form of map. It’s limited because the keys must be atoms and because these maps don’t have Dict capabilities. The name of the module becomes the name of the map type.
Inside the module, you use the defstruct macro to ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access