liveBook · Manning

Struct

As explained in Elixir in Action, Third Edition

An Elixir struct is a map-like data structure associated with a module and containing a defined set of fields.

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

How Elixir in Action, Third Edition covers it

How deep it goes
Explains definition, construction, access, pattern matching, updating, internal map behavior, and selected failure modes.
Examples
Demonstrates Fraction arithmetic and a TodoList that assigns incremental IDs while storing entries by ID.
What it assumes
Assumes maps and modules as the surrounding mechanisms for grouping fields and implementing data operations.
What you can do after
Builds module-backed data abstractions with defined fields, pattern-matched operations, and immutable updates.
How it connects
Connects structs with maps, modules, pattern matching, immutable updates, and protocols.

Also explained in

Compare how 14 books explain struct →

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.