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.
# 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
- Read
defstruct: Declare struct fields and defaults. - Read
@enforce_keys: Require selected fields when a struct is built. - 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_keysadd 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.
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
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
- Structs give maps a domain shape.
- Attributes document and constrain modules.
- Pattern-match only the fields a function needs.