Skip to content

Commit 06ff083

Browse files
authored
Update structs.md (#14683)
1 parent cacdbf6 commit 06ff083

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

lib/elixir/pages/getting-started/structs.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,28 @@ iex> %User{} = %{}
7676

7777
For more details on creating, updating, and pattern matching structs, see the documentation for `%/2`.
7878

79+
## Dynamic struct updates
80+
81+
When you need to update structs with data from keyword lists or maps, use `Kernel.struct!/2`:
82+
83+
```elixir
84+
iex> john = %User{name: "John", age: 27}
85+
%User{age: 27, name: "John"}
86+
iex> updates = [name: "Jane", age: 30]
87+
[name: "Jane", age: 30]
88+
iex> struct!(john, updates)
89+
%User{age: 27, name: "Jane"}
90+
```
91+
92+
`struct!/2` will raise an error if you try to set invalid fields:
93+
94+
```elixir
95+
iex> struct!(john, invalid: "field")
96+
** (KeyError) key :invalid not found in: %User{age: 27, name: "John"}
97+
```
98+
99+
Use the map update syntax (`%{john | name: "Jane"}`) when you know the exact fields at compile time. Always use `struct!/2` instead of `Map` functions to preserve struct integrity.
100+
79101
## Structs are bare maps underneath
80102

81103
Structs are simply maps with a "special" field named `__struct__` that holds the name of the struct:

0 commit comments

Comments
 (0)