DEV Community

Ryan Will
Ryan Will

Posted on • Originally published at til.ryanwill.dev on

3 1

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.

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay