Pattern matching
| The = operator | |
| Destructure data | |
| Pin with ^ | |
| When nothing matches (MatchError) |
The = operator
The equals sign matches the right side against the left side pattern.
A bare name matches anything and binds it for later lines.
Rebinding the same name later simply matches again, which is why Elixir calls it matching rather than assigning.
x = 1
x = x + 1
x
Destructure data
Patterns mirror the shape of the data they unpack.
Tuples match by position, lists split head from tail, and maps match by key.
Each name inside the pattern binds its piece in a single step.
{:ok, code} = {:ok, 200}
[head | tail] = [1, 2, 3]
%{name: who} = %{name: "Ada", age: 36}
Pin with ^
The pin operator freezes a bound name so it must equal its current value.
Without the pin, the name would simply rebind to the new value.
Pinning turns an accidental rebind into a loud and early mismatch.
expected = 200
{:ok, ^expected} = {:ok, 200}
When nothing matches (MatchError)
A match that cannot fit raises MatchError and stops with a clear report.
This strictness catches wrong shapes early instead of spreading bad data further.
The line below fails because an error tuple never equals an ok pattern.
{:ok, value} = {:error, :down}
Next: case
Article author: Arthur Isaev