Assignments with the Match Operator

Learn how to use the match operator for assignments in Elixir.

We'll cover the following

In most languages, = is the assignment operator. To assign the value 1 to a variable a, depending on the language, we write something like a = 1. The value on the right-hand side is assigned to the variable on the left-hand side.

Examples

But in Elixir, = isn’t the assignment operator but a match operator. Let’s elaborate it first with a practical example:

iex> a = 1 
1
iex> a + 3 
4

Most programmers would look at this code and say, "Okay, we assign 1 to variable a, then we add 3 to it, which makes a equal to 4.”

But when it comes to Elixir, they’d be wrong. In Elixir, the equals sign isn’t an assignment. Instead, it’s like an assertion. It succeeds if Elixir can find a way of making the left-hand side equal the right-hand side.

Get hands-on with 1400+ tech skills courses.