← Back to lesson 17: Give domain data a shape

Give domain data a shape: full examples and further reading

The original lesson material is preserved here for reference. The main notebook focuses on this lesson's core question.

Define a struct with module documentation, required keys, and a function that matches it.

Build a Book struct and run a function that checks its page count.

Run this first

Run it once, change one input, and compare the new result.

Original full example
# Define documented data and one operation
defmodule Book do
  @moduledoc "A small book record."
  @enforce_keys [:title]
  defstruct [:title, pages: 0]
  def long?(%__MODULE__{pages: pages}), do: pages >= 300
end

book = struct!(Book, title: "River", pages: 320)
{book.title, Book.long?(book)}

The result is {"River", true}.

Steps for the full example

  1. Read defstruct: Declare struct fields and defaults.
  2. Read @enforce_keys: Require selected fields when a struct is built.
  3. Read %__MODULE__{}: Refer to the current module's struct inside its functions.

Original lesson notes

Run the example first. Predict one result, then change one input and run it again.

A struct is a map with a fixed module name and declared fields.

Attributes such as @moduledoc, @doc, and @enforce_keys add compile-time information.

Symbols and terms
defstruct
Declare struct fields and defaults.
@enforce_keys
Require selected fields when a struct is built.
%__MODULE__{}
Refer to the current module's struct inside its functions.
struct
A struct is a map with a fixed module name and declared fields.
module attribute
Attributes such as @moduledoc, @doc, and @enforce_keys add compile-time information.
struct pattern
%Book{pages: pages} matches only a Book struct and extracts one field.

Original full exercise

Add an author field and build a book with that field.

Exercise starter
defmodule NoteBook do
  defstruct [:title, ____]
end

struct!(NoteBook, title: "North", ____: "Maya")

Return a NoteBook struct whose author is "Maya".

Show hint

Use the field name author in both blanks.

Show original answer
Reference answer
defmodule NoteBook do
  defstruct [:title, :author]
end

struct!(NoteBook, title: "North", author: "Maya")
Is every map a Book struct?

No. A struct carries its module name and declared fields.

Original lesson takeaways
Design trade-offs and language comparisons
Original course references