Elixir basics · Lesson 16 (open contents)
Give domain data a shape
Define a struct with module documentation, required keys, and a function that matches it.
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}.
Read from the first line down
- 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.
Symbols are not secret signs
defstructDeclare struct fields and defaults.
@enforce_keysRequire selected fields when a struct is built.
%__MODULE__{}Refer to the current module's struct inside its functions.
Match each name to its meaning
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.
Why these forms are useful
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.
Close the answer and try
Add an author field and build a book with that field.
defmodule NoteBook do
defstruct [:title, ____]
end
struct!(NoteBook, title: "North", ____: "Maya")Target result: Return a NoteBook struct whose author is "Maya".
Stuck? Read one hint
Use the field name author in both blanks.
After you run it, see one answer
defmodule NoteBook do
defstruct [:title, :author]
end
struct!(NoteBook, title: "North", author: "Maya")Think about it: Is every map a Book struct?
No. A struct carries its module name and declared fields.
Remember these three lines
- 1
Structs give maps a domain shape.
- 2
Attributes document and constrain modules.
- 3
Pattern-match only the fields a function needs.