Michael Mattheakis Blog

How To Get A Struct's Type In Elixir

There are a couple of ways to retrieve the type of a struct in Elixir. Let’s say we have a struct called Foo:

defmodule Foo do
  defstruct [:value]
end

Foo has one field named :value. When we say the “type” of a struct, we really mean the module in which the struct was defined. In this case, that module is Foo.


Way #1: Accessing the struct field:

iex> foo = %Foo{value: "hello"}
%Foo{value: "hello"}
iex> foo.__struct__
Foo

Way #2: Pattern matching using map synatx:

iex> %{__struct__: struct_type} = foo
%Foo{value: "hello"}
iex> struct_type
Foo

You may have seen this pattern matching synatx used with maps in Elixir - you can use it with structs too! Structs in Elixir are maps with some extra features added on.


Way #3: Pattern matching using struct synatx:

iex> %struct_type{} = foo
%Foo{value: "hello"}
iex> struct_type
Foo

This is a syntax trick that lets you easily assign the struct type to a variable. The idea here is that it lets you intuitively match against the struct type that’s printed in between the % and curly braces.