How to get the struct type in Elixir

Article autor
September 9, 2025
How to get the struct type in Elixir
Elixir Newsletter
Join Elixir newsletter

Subscribe to receive Elixir news to your inbox every two weeks.

Oops! Something went wrong while submitting the form.

Table of contents

So you don’t know what’s the type of struct you’re passing somewhere? Maybe it can be one of few types and you have to distinguish them? Or any other reason… But it’s about checking the struct type. Just use one of the coolest Elixir features - pattern matching!

Check this out:

iex(1)> some_struct = %MyApp.User{}
iex(2)> %type{} = some_struct
iex(3)> type
MyApp.User

That’s just a hook point for a bunch of cool facilities, like function call by module type:

defmodule Chess.Bishop do
  def move(piece), do: move_diagonally(piece)
end

defmodule Chess.Rook do
  def move(piece), do: move_straight(piece)
end

defmodule Chess.Pawn do
  def move(piece), do: move_forward(piece)
end

And then in console:

iex(1)> piece = get_chess_piece()
iex(2)> %module{} = piece
iex(3)> module.move(piece)

Have fun! If you'd like to learn more about structs in Elixir, check this blog post: Elixir Trickery: Cheating on Structs, And Why It Pays Off.

Related posts

Dive deeper into this topic with these related posts

No items found.

You might also like

Discover more content from this category

How to copy and paste within a terminal in macOS or Linux?

Sometimes we want to store some piece of information while using a terminal, for example, a result of an executed command. We usually save it into some temporary file which is going to be deleted after all. There’s a better way.

How to safely handle related database operations with Ecto Multi

Sometimes you need to do some database operations at once. A simple example: User-A transfers money to User-B. Updating just one balance at the time creates a risk of data desynchronization. What if the first DB operation goes well but updating the second user’s data fails? Sounds like a hard to catch vulnerability.

How to override Kernel macros

The macro mechanism in Elixir is not only an interesting metaprogramming feature - in fact, it is at the language's very core. And the more awesome fact is that, using macros, you can override the algorithm of defining functions itself!