summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJonatan Männchen <jonatan@maennchen.ch>2021-04-09 13:17:36 +0200
committerGitHub <noreply@github.com>2021-04-09 13:17:36 +0200
commit81f37bfdc3dd6352be41676cfd2adbf26285f23c (patch)
tree366de1e04e6388da1386f6a653bcc9ac1cac5061
parent19cf9eaa0e127b534589cc12584873df0286e9fd (diff)
downloadelixir-81f37bfdc3dd6352be41676cfd2adbf26285f23c.tar.gz
Add Struct Pattern Matching Guide (#10889)
-rw-r--r--lib/elixir/pages/patterns-and-guards.md37
1 files changed, 37 insertions, 0 deletions
diff --git a/lib/elixir/pages/patterns-and-guards.md b/lib/elixir/pages/patterns-and-guards.md
index 01d88c5da..446063a2a 100644
--- a/lib/elixir/pages/patterns-and-guards.md
+++ b/lib/elixir/pages/patterns-and-guards.md
@@ -205,6 +205,43 @@ iex> %{} = %{name: "meg"}
Finally, note map keys in patterns must always be literals or previously bound variables matched with the pin operator.
+### Structs
+
+Structs may appear in patterns using the percentage sign, the struct module name or a variable followed by the curly brackets syntax (`%{}`).
+
+Given the following struct:
+
+```elixir
+defmodule User do
+ defstruct [:name]
+end
+```
+
+Here is an example where all keys match:
+
+```iex
+iex> %User{name: name} = %User{name: "meg"}
+%User{name: "meg"}
+iex> name
+"meg"
+```
+
+If an unknown key is given, there will be an error:
+
+```iex
+iex> %User{type: type} = %User{name: "meg"}
+** (CompileError) iex:6: unknown key :type for struct User
+```
+
+The struct name can be extracted when putting a variable instead of a module name:
+
+```
+iex> %struct_name{} = %User{name: "meg"}
+%User{name: "meg"}
+iex> struct_name
+User
+```
+
### Binaries
Binaries may appear in patterns using the double less-than/greater-than syntax ([`<<>>`](`<<>>/1`)). A binary in a pattern can match multiple segments at the same, each with different type, size, and unit: