Pattern Match Struct's Name

ryanwilldev

Ryan Will

Posted on January 21, 2020

Pattern Match Struct's Name

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.

💖 💪 🙅 🚩
ryanwilldev
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.

Related

TIL: about Entity Relationship Schemas
TIL IEX Console #2
elixir TIL IEX Console #2

May 12, 2022

Pattern Match Struct's Name
elixir Pattern Match Struct's Name

January 21, 2020

Pattern match in with clause 🤯
elixir Pattern match in with clause 🤯

January 15, 2020