Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions getting-started/structs.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,27 @@ iex> Map.keys(john)
```

Structs alongside protocols provide one of the most important features for Elixir developers: data polymorphism. That's what we will explore in the next chapter.

## Default values and required keys

If you don't specify a default key value when defining a struct, `nil` will be assumed:

```iex
iex> defmodule Product do
...> defstruct [:name]
...> end
iex> %Product{}
%Product{name: nil}
```

You can also enforce that certain keys have to be specified when creating the struct:

```iex
iex> defmodule Car do
...> @enforce_keys [:make]
...> defstruct [:model, :make]
...> end
iex> %Car{}
** (ArgumentError) the following keys must also be given when building struct Car: [:make]
expanding struct: Car.__struct__/1
```