💧 Elixir Beginner

What is pattern matching in Elixir?

Answer

Pattern matching is one of Elixir's most important features. The = operator in Elixir is not assignment — it is a match operator. It attempts to match the right side against the left side pattern. x = 1 binds x to 1. {a, b} = {1, 2} binds a=1 and b=2. [head | tail] = [1, 2, 3] binds head=1, tail=[2,3]. Failed match raises MatchError. Use in function clauses: def handle({:ok, value}), do: process(value); def handle({:error, reason}), do: log(reason). Pattern matching in case: case response do {:ok, data} -> data; {:error, _} -> nil end. Pin operator ^: use existing value instead of rebinding: ^x = 1 — matches only if the value equals the current x. Pattern matching makes Elixir code extraordinarily expressive and eliminates most conditional logic.