You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: lib/elixir/pages/getting-started/structs.md
+8-8Lines changed: 8 additions & 8 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -78,25 +78,25 @@ For more details on creating, updating, and pattern matching structs, see the do
78
78
79
79
## Dynamic struct updates
80
80
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`:
82
82
83
83
```elixir
84
84
iex> john = %User{name:"John", age:27}
85
85
%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"}
88
90
```
89
91
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:
91
93
92
94
```elixir
93
-
iex> fields = [name:"Jane", invalid:"field"]
94
-
[name:"Jane", invalid:"field"]
95
-
iex>struct!(john, fields)
95
+
iex>struct!(john, invalid:"field")
96
96
** (KeyError) key :invalidnot found in: %User{age:27, name:"John"}
97
97
```
98
98
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.
0 commit comments