#19: What are ^Pinned Values?

Photo by Sarah Dao on Unsplash

#19: What are ^Pinned Values?

·

1 min read

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.