diff --git a/README.md b/README.md index 30e59e3..da8f847 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really warrant a full blog post. These are mostly things I learn by pairing with smart people at [Hashrocket](http://hashrocket.com/). -_489 TILs and counting..._ +_490 TILs and counting..._ --- @@ -100,6 +100,7 @@ _489 TILs and counting..._ - [Pattern Matching In Anonymous Functions](elixir/pattern-matching-in-anonymous-functions.md) - [Quitting IEx](elixir/quitting-iex.md) - [Replace Duplicates In A Keyword List](elixir/replace-duplicates-in-a-keyword-list.md) +- [Requiring Keys For Structs](elixir/requiring-keys-for-structs.md) - [Reversing A List](elixir/reversing-a-list.md) - [Reversing A List - Part 2](elixir/reversing-a-list-part-2.md) - [Root Directory Of A Project](elixir/root-directory-of-a-project.md) diff --git a/elixir/requiring-keys-for-structs.md b/elixir/requiring-keys-for-structs.md new file mode 100644 index 0000000..343e007 --- /dev/null +++ b/elixir/requiring-keys-for-structs.md @@ -0,0 +1,39 @@ +# Requiring Keys For Structs + +When defining a +[`struct`](http://elixir-lang.org/getting-started/structs.html) in Elixir, +we may want to ensure that certain values are provided. We can require that +certain keys are used in the creation of a struct with the +[`@enforce_keys`](https://hexdocs.pm/elixir/Kernel.html#defstruct/1) +attribute. Here is an example of a `Name` struct. + +```elixir +defmodule Name do + @enforce_keys [:first, :last] + defstruct [:first, :middle, :last] +end +``` + +With this defined, we can create a struct that uses all of the keys. + +```elixir +> jack = %Name{first: "Jack", middle: "Francis", last: "Donaghy"} +%Name{first: "Jack", last: "Donaghy", middle: "Francis"} +``` + +We can also ignore `:middle` and just provide the required keys. + +```elixir +> liz = %Name{first: "Liz", last: "Lemon"} +%Name{first: "Liz", last: "Lemon", middle: nil} +``` + +We cannot, however, omit any of the keys specified in `@enforce_keys`. If we +do omit any of them, Elixir will raise an error. + +``` elixir +> tracy = %Name{first: "Tracy"} +** (ArgumentError) the following keys must also be given when building struct Name: [:last] + expanding struct: Name.__struct__/1 + iex:6: (file) +```