liveBook · Manning

Defstruct macro

As explained in Elixir in Action, Third Edition

The defstruct macro defines the fields and initial values of a struct in an Elixir module.

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

How Elixir in Action, Third Edition covers it

How deep it goes
Explains definition, construction, access, pattern matching, updates, and compile-time field validation, but not custom protocols.
Examples
Uses a Fraction struct with numerator-like fields a and b to demonstrate construction, arithmetic, matching, updating, and errors.
What it assumes
Assumes familiarity with Elixir modules, maps, tuples, and pattern matching while contrasting structs with those representations.
What you can do after
Build data abstractions from scratch using defstruct, struct syntax, field access, pattern matching, and immutable updates.
How it connects
Connects structs with modules, maps, pattern matching, immutability, and compile-time validation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.