DEV Community

Ryan Will
Ryan Will

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

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)