Skip to content

Commit 323f546

Browse files
authored
Update structs.md
1 parent 6fd2181 commit 323f546

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

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

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -78,25 +78,25 @@ For more details on creating, updating, and pattern matching structs, see the do
7878

7979
## Dynamic struct updates
8080

81-
When you need to update structs with data from variables or external sources, use `struct!/2`:
81+
When you need to update structs with data from keyword lists or maps, use `Kernel.struct!/2`:
8282

8383
```elixir
8484
iex> john = %User{name: "John", age: 27}
8585
%User{age: 27, name: "John"}
86-
iex> struct!(john, name: "Jane", age: 30)
87-
%User{age: 30, name: "Jane"}
86+
iex> updates = [name: "Jane", age: 30]
87+
[name: "Jane", age: 30]
88+
iex> struct!(john, updates)
89+
%User{age: 27, name: "Jane"}
8890
```
8991

90-
Unlike the update syntax, `struct!/2` accepts data from maps and keyword lists, and will raise an error if you try to set invalid fields:
92+
`struct!/2` will raise an error if you try to set invalid fields:
9193

9294
```elixir
93-
iex> fields = [name: "Jane", invalid: "field"]
94-
[name: "Jane", invalid: "field"]
95-
iex> struct!(john, fields)
95+
iex> struct!(john, invalid: "field")
9696
** (KeyError) key :invalid not found in: %User{age: 27, name: "John"}
9797
```
9898

99-
Always use `struct!/2` instead of `Map` functions when working with structs, as functions like `Map.put/3` and `Map.merge/2` can break struct integrity. See the [`Kernel.struct!/2`](https://hexdocs.pm/elixir/Kernel.html#struct!/2) documentation for more details.
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.
100100

101101
## Structs are bare maps underneath
102102

0 commit comments

Comments
 (0)