The Match Operator =
In most languages the equals sign means "assign this value to this
variable". Elixir treats = differently and calls it the match
operator. Instead of "assign", read = as "try to match the
left-hand side against the right-hand side".
iex> x = 5 (1)
5
iex> 5 = x (2)
5
iex> 6 = x (3)
** (MatchError) no match of right hand side value: 5
| 1 | A variable on the left is unbound, so Elixir binds x to 5. |
| 2 | Both sides have the same value, the match succeeds. |
| 3 | 6 cannot match 5, so Elixir raises a MatchError. |
= is the gateway into pattern matching, one of Elixir’s
defining features. The full story (destructuring tuples, lists, maps
and strings, the pin operator, wildcards) lives in the
Pattern Matching
chapter.
|