|
| 1 | +# Requiring Keys For Structs |
| 2 | + |
| 3 | +When defining a |
| 4 | +[`struct`](http://elixir-lang.org/getting-started/structs.html) in Elixir, |
| 5 | +we may want to ensure that certain values are provided. We can require that |
| 6 | +certain keys are used in the creation of a struct with the |
| 7 | +[`@enforce_keys`](https://hexdocs.pm/elixir/Kernel.html#defstruct/1) |
| 8 | +attribute. Here is an example of a `Name` struct. |
| 9 | + |
| 10 | +```elixir |
| 11 | +defmodule Name do |
| 12 | + @enforce_keys [:first, :last] |
| 13 | + defstruct [:first, :middle, :last] |
| 14 | +end |
| 15 | +``` |
| 16 | + |
| 17 | +With this defined, we can create a struct that uses all of the keys. |
| 18 | + |
| 19 | +```elixir |
| 20 | +> jack = %Name{first: "Jack", middle: "Francis", last: "Donaghy"} |
| 21 | +%Name{first: "Jack", last: "Donaghy", middle: "Francis"} |
| 22 | +``` |
| 23 | + |
| 24 | +We can also ignore `:middle` and just provide the required keys. |
| 25 | + |
| 26 | +```elixir |
| 27 | +> liz = %Name{first: "Liz", last: "Lemon"} |
| 28 | +%Name{first: "Liz", last: "Lemon", middle: nil} |
| 29 | +``` |
| 30 | + |
| 31 | +We cannot, however, omit any of the keys specified in `@enforce_keys`. If we |
| 32 | +do omit any of them, Elixir will raise an error. |
| 33 | + |
| 34 | +``` elixir |
| 35 | +> tracy = %Name{first: "Tracy"} |
| 36 | +** (ArgumentError) the following keys must also be given when building struct Name: [:last] |
| 37 | + expanding struct: Name.__struct__/1 |
| 38 | + iex:6: (file) |
| 39 | +``` |
0 commit comments