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 is the name of the map type. Inside the module, you use the defstruct macro to define ...

Get Programming Elixir 1.3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.