Skip to content
Pattern Matching
step 1/5

Reading — step 1 of 5

Learn

~1 min readStrings and Pattern Matching

In Elixir, = isn't assignment — it's match. The left side describes a pattern; the right side is the value. If they match, any variables in the pattern get bound. If not, you get a MatchError.

{a, b} = {1, 2}    # a = 1, b = 2
[h | t] = [1, 2, 3] # h = 1, t = [2, 3]
%{name: n} = %{name: "Alice", age: 30}  # n = "Alice"

This powers everything in Elixir — function clauses, error handling, control flow:

case File.read("foo.txt") do
    {:ok, contents} -> IO.puts contents
    {:error, reason} -> IO.puts "oops: #{reason}"
end

The _ matches anything but doesn't bind. The ^ operator pins an existing value (useful when you want to match against a variable's current value, not rebind):

x = 1
^x = 1   # ok — matches
^x = 2   # MatchError

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…