A struct is a special kind of map associated with a module. The module defines one struct with a fixed set of fields and default values, giving data a more precise shape than an ordinary map. section 4.1.3 section 4.1.4
Structs provide map-like operations while adding identity and shape checks:
- Define fields with defstruct and create instances with %Module{} or a constructor function. section 4.1.4
- Access fields with dot syntax, as with maps. section 4.1.4
- Pattern-match on the module name and selected fields, including %Fraction{} to require a Fraction struct regardless of its contents. section 4.1.4
- Update instances with map-style syntax, producing a new struct rather than mutating the original. section 4.1.4
- Reject unknown fields during literal construction, and do not assume structs are Enumerable merely because they are maps internally. section 4.1.4
Fractions and a stateful to-do list
A Fraction module can define `defstruct a: nil, b: nil`, construct `%Fraction{a: 1, b: 2}`, and pattern-match in `value/1` or `add/2`. A TodoList struct can hold `next_id: 1` and `entries: %{}`, allowing `add_entry/2` to assign an ID, store the entry by ID, and return an updated list. section 4.1.4 section 4.2.1
Listing 4.7 Defining a structure (fraction.ex)
defmodule Fraction do defstruct a: nil, b: nil ... end
Shows the minimal module definition that establishes a struct's fields and defaults. section 4.1.4













