Skip to content
loading...

Pattern Match Struct's Name

twitter logo github logo Originally published at til.ryanwill.dev on ・1 min read  

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.

twitter logo DISCUSS
Classic DEV Post from Jul 2 '19

How to refill someone’s “cup?”

Sometimes we rely so much on our friends and coworkers that we often forget to ma...

Ryan Will profile image
Cultivating software. Aprendiendo español. Piensa más en lo que te fascina.