Skip to content

Commit f31ed61

Browse files
committed
Add Requiring Keys For Structs as an elixir til
1 parent 31ebf4e commit f31ed61

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really
77
warrant a full blog post. These are mostly things I learn by pairing with
88
smart people at [Hashrocket](http://hashrocket.com/).
99

10-
_489 TILs and counting..._
10+
_490 TILs and counting..._
1111

1212
---
1313

@@ -100,6 +100,7 @@ _489 TILs and counting..._
100100
- [Pattern Matching In Anonymous Functions](elixir/pattern-matching-in-anonymous-functions.md)
101101
- [Quitting IEx](elixir/quitting-iex.md)
102102
- [Replace Duplicates In A Keyword List](elixir/replace-duplicates-in-a-keyword-list.md)
103+
- [Requiring Keys For Structs](elixir/requiring-keys-for-structs.md)
103104
- [Reversing A List](elixir/reversing-a-list.md)
104105
- [Reversing A List - Part 2](elixir/reversing-a-list-part-2.md)
105106
- [Root Directory Of A Project](elixir/root-directory-of-a-project.md)

elixir/requiring-keys-for-structs.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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

Comments
 (0)