Elixir Pattern Matching
When You Get To Know That (=) Stopped Meaning Assignment
If you come from JavaScript, Python, Ruby, Java, or most other mainstream programming languages, there is a good chance your first encounter with this Elixir code will feel completely normal:
name = “Gordon”
You look at it and think:
“Easy. We assigned “Gordon” to name.”
Then Elixir calmly does something that makes you question your life choices:
1 = 1
That works.
Then:
1 = 2
And Elixir says:
**** (MatchError) no match of right hand side value: 2
At this point, the innocent-looking = has exposed itself.
It isn’t simply an assignment operator.
In Elixir, it is the match operator.
And understanding that difference is one of the moments where Elixir starts to feel less like “another programming language” and more like Elixir.
The official documentation describes pattern matching as a mechanism for asserting the shape of data and extracting values from data structures. It is one of the foundations of everyday Elixir programming.
Let’s take it apart properly.
1. First, forget what = means in other languages
Suppose you’re writing Python:
name = “Gordon”
You generally read that as:
Put “Gordon” inside the variable name.
In Elixir:
name = “Gordon”
there is certainly a binding happening, but the deeper idea is:
“Does the pattern on the left match the value on the right?”
Since name is an unbound variable, it can bind to the value:
name = “Gordon”
Now:
name
returns:
“Gordon”
So far, nothing seems particularly strange.
Let’s make things uncomfortable.
1 = 1
Result:
1
But:
1 = 2
Result:
** (MatchError) no match of right hand side value: 2
Why?
Because the left side is the literal pattern 1.
The right side evaluates to 2.
There is no match.
The Elixir documentation explicitly demonstrates this behavior: x = 1 binds x, while 2 = x fails once x contains 1.
So perhaps the better mental model is:
pattern = value
not:
variable = value
That small mental shift will save you a lot of confusion.
2. Pattern matching is not just comparison
Here’s where pattern matching becomes genuinely interesting.
Consider:
user = {“Gordon”, 25}
We could retrieve the pieces manually:
elem(user, 0)
elem(user, 1)
But Elixir lets us describe the structure we expect:
{name, age} = {“Gordon”, 25}
Now:
name
gives:
“Gordon”
and:
age
gives:
25
We didn’t tell Elixir:
“Take element 0 and put it into name.”
We described the structure:
{name, age}
and asked Elixir to match it against:
{“Gordon”, 25}
The structure matches.
The variables are bound.
And suddenly we have two values.
This is destructuring through pattern matching.
3. Elixir doesn’t just match values. It matches shapes.
Consider:
{name, age} = {“Gordon”, 25}
The tuple has two elements.
Our pattern also has two elements.
So it matches.
But:
{name, age} = {“Gordon”, 25, “Kenya”}
doesn’t work.
Why?
Because we’re trying to match:
2-element tuple
against:
3-element tuple
The shapes are different.
Elixir isn’t going to shrug and say:
“Close enough, I’ll figure it out.”
Nope.
It says:
MatchError
The official documentation shows the same principle: tuples with different sizes cannot match, and a tuple pattern cannot match a list.
This strictness is actually one of the reasons pattern matching is so useful.
Instead of writing code that accepts almost anything and then discovering later that something is wrong, we can describe the data we expect at the boundary of our code.
4. The coolest part: pattern matching can extract data
Consider an API response:
{:ok, user}
You could write:
response = {:ok, user}
But suppose you already know you only care about successful responses.
You can write:
{:ok, user} = response
Now user contains the value.
This is one of the most common patterns you’ll see in Elixir:
{:ok, result}
and:
{:error, reason}
For example:
case create_user(params) do
{:ok, user} ->
IO.puts(“Created #{user.name}”)
{:error, reason} ->
IO.puts(“Something went wrong: #{reason}”)
end
The pattern:
{:ok, user}
does two jobs.
It checks that the result is an :ok tuple.
And it extracts the second value into user.
That is a very Elixir-ish way of writing code.
5. This is where case starts becoming beautiful
Pattern matching isn’t confined to the = operator.
It is deeply integrated into Elixir’s control flow.
Consider:
case result do
{:ok, user} ->
“Welcome #{user.name}”
{:error, reason} ->
“Oops: #{reason}”
end
The case expression tries the patterns in order until one matches. The official documentation describes case precisely this way: it compares a value against multiple patterns and uses the first matching clause.
This means you can think of the code as:
“What did I receive?”
↓
{:ok, user}
│
└── success
{:error, reason}
│
└── failure
Instead of:
if result.status == “success” do
…
else
…
end
you’re describing the actual shape of the data.
And that is an important philosophical difference.
6. Function definitions can pattern match too
This is where things get even more interesting.
You don’t always need a giant case.
You can put patterns directly into function heads.
For example:
def greet({:user, name}) do
“Hello #{name}!”
end
Now:
greet({:user, “Gordon”})
returns:
“Hello Gordon!”
But the function isn’t just receiving some random value and checking it later.
Its function head says:
“I handle values shaped like {:user, name}.”
You can define another clause:
def greet(:guest) do
“Hello guest!”
end
Now:
greet({:user, “Gordon”})
uses the first clause.
And:
greet(:guest)
uses the second.
This is one of the places where Elixir’s functional style becomes particularly expressive.
Your function clauses become a description of the different shapes of input your function knows how to handle.
7. Lists have a special superpower
Lists become especially fun.
Suppose:
numbers = [10, 20, 30, 40]
We can split the first element from the rest:
[head | tail] = numbers
Now:
head
is:
10
and:
tail
is:
[20, 30, 40]
The | is telling us:
“I want the head separated from the rest of the list.”
You can picture it like this:
[10 | [20, 30, 40]]
↑ ↑
head tail
This tiny piece of syntax is fundamental to recursive programming in Elixir.
For example:
def sum([]) do
0
end
def sum([head | tail]) do
head + sum(tail)
end
Look closely.
The function is essentially saying:
If the list is empty:
return 0
If the list has:
head + tail
add head
recursively process tail
Pattern matching isn’t just helping us retrieve values.
It is helping us describe the algorithm.
8. The underscore: “I don’t care”
Sometimes the data contains something we don’t need.
Suppose:
{:ok, user, metadata}
but we only care about the user.
We can write:
{:ok, user, _metadata} = response
Or simply:
{:ok, user, _} = response
The underscore means:
“There is something here, but I don’t care about it.”
For example:
{_, age} = {“Gordon”, 25}
Now:
age
is:
25
But this won’t work:
_
The underscore is deliberately not a variable you can read later. The official documentation describes _ as a special pattern that cannot be bound or read.
It’s basically Elixir’s polite way of saying:
“Yes, I saw that. No, I don’t want it.”
9. Wait… variables can change?
This is where developers coming from functional-programming discussions sometimes get confused.
You might hear:
“Elixir has immutable data.”
Then you see:
x = 10
x = 20
and think:
“Excuse me?”
It works.
x = 10
x = 20
Now:
x
returns:
20
Elixir allows rebinding.
But that doesn’t mean the original integer changed.
Integers are immutable.
The binding simply changed.
The official documentation makes this distinction explicit: variables may be rebound, and the pin operator can be used when you want to match against the variable’s existing value instead.
This distinction matters.
Think:
value
↑
binding
rather than:
variable = box containing mutable value
That mental model fits Elixir much better.
10. Meet the pin operator: ^
Now suppose:
x = 10
And later you write:
x = 20
Elixir happily rebinds x.
But what if you want to say:
“No, Elixir. I mean the value that x already contains.”
That’s what the pin operator does:
^x = 20
If:
x = 10
then:
^x = 20
fails.
Why?
Because:
^x
means:
“Match against the existing value of x.”
So this:
x = 10
case 10 do
^x ->
“Yes!”
end
matches.
But:
x = 10
case 20 do
^x ->
“Yes!”
end
doesn’t.
The pin operator is especially useful when you already have a value and want pattern matching to compare against that value rather than create a new binding.
11. Pattern matching can verify data for you
Imagine you have:
response = {:ok, 200, “Everything worked”}
You could manually check:
if elem(response, 0) == :ok do
…
end
But that’s clumsy.
Pattern matching lets you express the expectation directly:
{:ok, status, message} = response
Now you’ve simultaneously asserted:
- it is a tuple
- the tuple has three elements
- the first element is :ok
- the second value should be bound to status
- the third value should be bound to message
That’s a lot of information in one line.
And if the shape is wrong, Elixir tells you immediately.
12. Maps make this even more useful
Suppose:
user = %{
name: “Gordon”,
age: 25,
country: “Kenya”
}
You can match specific keys:
%{name: name} = user
Now:
name
is:
“Gordon”
Notice something important.
We didn’t have to specify every key:
%{name: name, age: age, country: country} = user
We can match only the portion we care about.
That makes map pattern matching extremely useful when dealing with larger structures.
For example:
def welcome(%{name: name}) do
“Welcome #{name}!”
end
The function doesn’t care about all the other fields.
It only requires that the incoming map has a :name key.
13. Pattern matching is one reason Elixir error handling feels different
Consider a typical result:
{:ok, value}
or:
{:error, reason}
This convention works beautifully with pattern matching.
For example:
case File.read(“config.json”) do
{:ok, contents} ->
IO.puts(contents)
{:error, reason} ->
IO.puts(“Could not read file: #{reason}”)
end
We’re not checking some mysterious status field.
We’re matching the actual result.
That makes failure paths explicit.
And this style extends throughout the Elixir and Erlang ecosystem.
14. with takes the idea even further
Pattern matching becomes especially powerful when several operations must succeed.
For example:
with {:ok, user} <- find_user(id),
{:ok, account} <- find_account(user),
{:ok, payment} <- create_payment(account) do
{:ok, payment}
else
{:error, reason} ->
{:error, reason}
end
This reads almost like a conversation:
Find the user.
Get Okall Gordon’s stories in your inbox
Join Medium for free to get updates from this writer.
↓
Did we get {:ok, user}?
Yes?
↓
Find the account.
↓
Did we get {:ok, account}?
Yes?
↓
Create the payment.
If one of those patterns doesn’t match, the with expression takes the failure path.
This is one of those moments where pattern matching stops feeling like a language feature and starts feeling like a way of expressing program logic.
15. Pattern matching is not the same thing as ==
This distinction is worth remembering.
Elixir has comparison operators such as:
==
and:
===
Those are for comparison.
Pattern matching is different:
=
For example:
1 == 1.0
can be:
true
while:
1 === 1.0
is:
false
Pattern matching has its own rules.
For example:
x = 1
binds x.
And:
^x = 1
matches against the existing value.
So don’t look at:
=
and automatically translate it to:
“assignment.”
In Elixir, the better translation is:
“match this pattern against this value.”
16. Pattern matching can make invalid states fail early
This is one of the reasons I personally find it so powerful.
Suppose your application expects:
{:ok, user}
but somewhere unexpectedly receives:
{:error, “database unavailable”}
If you write:
{:ok, user} = result
you don’t silently continue with a broken assumption.
The match fails.
That can be extremely useful.
It forces you to confront the fact that your assumption about the data was wrong.
Of course, whether you want a failed match or want to handle the failure gracefully depends on the situation. Pattern matching is not an excuse to turn every possible error into a crash.
The important idea is that the code makes its expectations explicit.
17. Pattern matching and guards: a powerful combination
Sometimes the shape isn’t enough.
Suppose we want to handle positive integers:
def process(number) when is_integer(number) and number > 0 do
…
end
Here we have:
Pattern
+
Guard
Pattern matching answers:
“Does the value have the structure I’m expecting?”
The guard answers:
“Does it also satisfy this additional condition?”
Elixir’s documentation describes guards as a way to add additional checks to patterns, within the set of expressions permitted in guards.
For example:
def classify(number) when number > 0 do
:positive
end
def classify(number) when number < 0 do
:negative
end
def classify(0) do
:zero
end
Now the function clauses themselves describe the cases.
That’s incredibly readable once you’re used to it.
18. And this is where Elixir starts to feel different
A beginner might write:
def classify(number) do
if number > 0 do
:positive
else
if number < 0 do
:negative
else
:zero
end
end
end
It works.
But Elixir gives us another way:
def classify(number) when number > 0, do: :positive
def classify(number) when number < 0, do: :negative
def classify(0), do: :zero
Now the function reads almost like a specification.
positive number → :positive
negative number → :negative
zero → :zero
This is one reason Elixir developers often favor pattern matching and guards over deeply nested conditional logic. The official documentation explicitly notes this preference when introducing case, cond, and if.
19. Pattern matching and processes
Now let’s connect this to one of the things that makes Elixir really special.
BEAM processes communicate through messages.
A process might receive:
{:deposit, 500}
Another message might be:
{:withdraw, 100}
Your code can match on the message shape:
receive do
{:deposit, amount} ->
IO.puts(“Depositing #{amount}”)
{:withdraw, amount} ->
IO.puts(“Withdrawing #{amount}”)
end
That means pattern matching becomes part of the communication model.
You’re effectively saying:
“If someone sends me a deposit message, I know exactly what that message looks like.”
This same idea is fundamental to OTP abstractions such as GenServer. Messages are matched and dispatched to the appropriate handling logic; Elixir’s ecosystem builds a huge amount of functionality on top of these simple ideas.
And suddenly that little {} syntax from your first Elixir tutorial is connected to concurrency.
Not bad for a couple of curly braces.
20. The funny thing about pattern matching
At first, pattern matching looks like a syntax convenience.
You think:
“Okay, cool. I can pull values out of tuples.”
Then you learn:
case
Then:
def function(pattern)
Then:
with
Then:
receive
Then:
GenServer
And eventually you realize:
“Wait a minute. Pattern matching is everywhere.”
That’s not an accident.
Pattern matching is one of the core ideas around which Elixir’s programming style is built.
The official learning material positions pattern matching alongside the language’s broader functional and OTP foundations, and the language documentation treats patterns and guards as a fundamental part of Elixir’s semantics.
21. A practical example: handling a payment
Let’s make this more realistic.
Imagine you’re building a payment system.
Your payment function returns:
{:ok, transaction}
or:
{:error, reason}
You could write:
case Payments.create_payment(params) do
{:ok, transaction} ->
notify_customer(transaction)
{:error, :insufficient_funds} ->
show_error(“You don’t have enough money.”)
{:error, reason} ->
log_error(reason)
end
Look at how much business logic is encoded in the patterns:
{:ok, transaction}
means:
Successful payment.
{:error, :insufficient_funds}
means:
Payment failed specifically because of insufficient funds.
{:error, reason}
means:
Some other failure happened.
We don’t need:
if response.status == …
followed by another check, followed by another check.
The shape of the data drives the control flow.
That is one of the most important ideas to take away.
22. A common beginner mistake
People sometimes start doing this:
[_, _, _, _, _, _, _, _, _, user] = enormous_nested_structure
Technically, pattern matching may allow it.
But just because Elixir lets you do something doesn’t mean your future teammates will send you flowers for doing it.
Pattern matching should make code clearer, not turn it into a treasure hunt.
Compare:
[_, _, _, _, _, _, _, _, _, user] = data
with something more deliberate:
%{user: user} = data
The second version tells the reader what you’re actually looking for.
A useful rule is:
Use pattern matching to express intent, not to show off how many data structures you can destroy in one line.
The Elixir community has had plenty of discussions around overly aggressive destructuring for exactly this reason. Pattern matching is powerful, but readability still matters.
23. Another common mistake: forgetting that variables rebind
Consider:
x = 10
x = 20
x
Some developers coming from Erlang may initially expect this to fail because Erlang variables are single-assignment.
Elixir is different: variables can be rebound.
But when you’re matching against an existing variable, you use:
^x
So:
x = 10
^x = 10
works.
While:
x = 10
^x = 20
fails.
Remember:
x → bind/rebind
^x → match against existing value
That tiny caret is doing important work.
24. A useful mental model
Whenever you see:
pattern = value
ask yourself three questions.
Question 1: What is the shape?
Is it:
{a, b}
a list:
[a | rest]
a map:
%{name: name}
or something else?
Question 2: What values are being asserted?
For example:
{:ok, result}
isn’t just extracting result.
It is asserting that the first element is exactly :ok.
Question 3: Which values are being extracted?
Variables inside the pattern capture the pieces you’re interested in.
For example:
{:ok, user} = result
means:
Assert :ok
↓
Extract user
Once you start thinking this way, pattern matching becomes much easier.
25. Pattern matching is really about describing data
This is probably the most important lesson.
Instead of thinking:
“How do I get the value I need out of this data?”
Elixir often encourages you to think:
“What does the data I want look like?”
For example:
{:ok, user}
instead of:
result = …
status = elem(result, 0)
user = elem(result, 1)
if status == :ok do
…
end
Or:
[head | tail]
instead of manually calculating indexes.
Or:
%{name: name}
instead of reaching into the map later.
This is a different way of thinking about programming.
And once it clicks, it becomes addictive.
26. Pattern matching isn’t magic
It can feel magical when you first see:
{:ok, user} = get_user()
But there is no magic involved.
The left side describes a pattern.
The right side produces a value.
Elixir attempts to match them.
If they match:
success
If they don’t:
MatchError
The official documentation is very explicit about this semantics: unbound variables in patterns can become bound when matching succeeds, while a failed match raises an error in contexts such as the match operator.
The more you understand the rules, the less magical it becomes.
And ironically, that’s when it becomes even more impressive.
27. The five pieces I would memorize
If you’re learning Elixir, don’t try to memorize every possible pattern immediately.
Start with these:
1. Basic matching
x = 10
2. Tuple matching
{:ok, value} = {:ok, 42}
3. List decomposition
[head | tail] = [1, 2, 3]
4. Map matching
%{name: name} = user
5. Pinning
^x = value
Once these become natural, you’ll start recognizing patterns everywhere in Elixir code.
28. The bigger picture
Pattern matching isn’t just a cute feature that lets us write shorter code.
It influences how Elixir applications are designed.
It encourages developers to represent states explicitly:
{:ok, value}
{:error, reason}
It makes function clauses communicate their expected inputs:
def process(%User{} = user)
It makes control flow data-oriented:
case result do
{:ok, value} -> …
{:error, reason} -> …
end
It helps with recursive algorithms:
def walk([]), do: …
def walk([head | tail]), do: …
It participates in message handling:
receive do
{:event, payload} -> …
end
And it gives us a concise way to destructure complex data.
That’s why learning pattern matching properly is worth the effort.
29. One final way to think about it
Imagine you are a security guard.
Someone walks through the door carrying:
{:employee, “Gordon”, :backend}
You have a rule:
{:employee, name, :backend}
You don’t need to ask:
“Are you an employee?”
Then:
“What’s your name?”
Then:
“Are you from backend?”
You simply look at the shape.
If it matches:
{:employee, name, :backend}
you let the person through and now you know:
name
If they show up as:
{:guest, “Gordon”}
the pattern doesn’t match.
The data itself determines what happens.
That’s pattern matching.
Conclusion
The first time you see:
{name, age} = {“Gordon”, 25}
it can look like a nicer way of assigning variables.
It isn’t.
It is a much more powerful idea:
Describe the shape of the data you expect, match against it, and extract the pieces you need.
Once you understand that, a lot of Elixir starts making more sense.
Suddenly:
case
makes more sense.
Function clauses make more sense.
with makes more sense.
{:ok, value} and {:error, reason} make more sense.
Lists and recursion make more sense.
Message passing starts making more sense.
And eventually you look at something like:
def handle_info({:payment_received, payment}, state) do
…
end
and realize that there are actually several Elixir ideas hiding inside one tiny function head.
That’s the beauty of the language.
Elixir doesn’t always ask you to write more instructions.
Sometimes it asks you to describe the problem more precisely.
And once you do that, the code almost seems to know what you meant.
A small challenge for you
Before you leave, open IEx and try to predict what happens with each of these:
{name, age} = {“Gordon”, 25}
{:ok, value} = {:ok, 42}
[head | tail] = [1, 2, 3, 4]
%{name: name} = %{name: “Gordon”, age: 25}
And finally:
x = 10
^x = 10
Then deliberately break each one.
Try:
{:ok, value} = {:error, :boom}
Try:
[head | tail] = []
Try:
x = 10
^x = 20
Don’t just read the errors.
Make friends with them.
A MatchError isn’t Elixir being angry at you.
It’s Elixir saying:
“You told me this data would look like this. It doesn’t.”
And honestly, that’s a pretty useful friend to have.




