The defstruct macro defines a module’s struct fields and initial values. It gives well-shaped data a named abstraction that can be instantiated, accessed, pattern-matched, and updated. section 4.1.4
Listing 4.7 Defining a structure (fraction.ex)
defmodule Fraction do defstruct a: nil, b: nil ... end
Define a Fraction struct with fields a and b, both initially nil. section 4.1.4
A struct supports the following implementation patterns:
- Instantiate it with %Fraction{a: 1, b: 2}, producing a value named for its defining module. section 4.1.4
- Access fields like map fields, or pattern-match only the fields a function needs. section 4.1.4
- Update an instance with map-style syntax, creating a new struct rather than mutating the original. section 4.1.4
- Reject unknown fields during compilation, catching shape errors that a regular map would permit. section 4.1.4
Fraction operations
Fraction.new/2 can return %Fraction{a: a, b: b}; Fraction.value/1 pattern-matches those fields, and Fraction.add/2 combines two matching Fraction structs. section 4.1.4
