#19: What are ^Pinned Values?
Pinned values in Elixir allow you to reference existing variables within a pattern match. By using the pin operator ^
, you can ensure that a variable's value is used as-is in the pattern match, rather than being treated as a new variable binding.
Basic Pinned Value:
# Define a variable
var = :match
# Using the pin operator to reference the existing variable in the pattern match
^var = :match
# Output: :match
# Attempting to match a different value will result in a MatchError
# ^var must match the existing value of var
^var = :no_match
# MatchError: no match of right hand side value: :no_match
Pinned Values in Tuple Matching:
# Define variables
var = :match
second = :other
# Using pinned values in tuple matching
[^var, second] = [:match, :other]
# Output: :other
Pinned Values with Maps:
# Define a map
map = %{a: 1}
# Using pinned values in map matching
^map = %{a: 1}
# Output: %{a: 1}
# Attempting to match a different map will result in a MatchError
^map = %{a: 1, b: 2}
# MatchError: no match of right hand side value: %{a: 1, b: 2}
Pinned values in Elixir provide a way to ensure that specific variables retain their values during pattern matching, offering control and predictability in pattern-matching scenarios.
Subscribe to my newsletter
Read articles from Stephan Yu directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Stephan Yu
Stephan Yu
I am a full-stack developer from Austria who has studied and worked in many countries including the UK, Australia, and the US. I have worked extensively with Ruby on Rails, React, and Typescript, and I am also building projects using Elixir and Phoenix.