Pattern Match Struct's Name
Ryan Will
Posted on January 21, 2020
If we define the following struct.
defmodule StructTest do
defstruct [:foo]
end
We can use pattern matching to capture the name of the struct in a variable.
%name{} = %StructTest{}
name # StructTest
The struct’s name could also be pattern matched in a function clause.
def print_name(%module_name{}) do
IO.puts(module_name)
end
print_name(%StructTest{}) # StructTest
This is used in Elixir’s Access Module to dynamically call the fetch/2
function on a struct’s module.
💖 💪 🙅 🚩
Ryan Will
Posted on January 21, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.