📎 Webclip
Elixir Structs are maps with checks and default values
Structs are presented as an extension of maps in Elixir. They keep key-value storage, add default values, and let code rely on a known set of fields when creating and matching data.
Reading notes#
- Structs extend maps and add compile-time checks plus default values.
- Dot syntax raises an error when a key is missing, while bracket syntax returns nil.
- Dot syntax assumes atom keys; when keys are strings, bracket syntax is the option shown.
- A struct defined with defstruct can supply defaults, such as age and name in User.
- Creating %User{} fills in default values for unspecified fields.
- Matching on %User{} or %Admin{} in case checks the struct type through the hidden struct field.
- If a struct used in a match is not defined, Elixir raises a compile-time error.
- @enforce_keys can require that certain fields be given when building a struct.
- Keys not listed in the struct cause a KeyError when used with %User{}.
- Required keys and optional keys can coexist, with defaults used for optional fields.
- Directly setting struct can bypass the usual struct checks, although the text says this should not be abused.
