How to get the struct type in Elixir

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!

Table of contents

    Check this out:

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

    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)
    defmodule Chess.Rook do
      def move(piece), do: move_straight(piece)
    defmodule Chess.Pawn do
      def move(piece), do: move_forward(piece)

    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.

    Download our ebook
    Oskar Legner
    Oskar Legner Elixir & React Developer

    Read more
    on #curiosum blog

    The little story of Elixir programming language

    The Elixir language, operating on an Erlang machine, is constantly gaining more and more followers. Where can these languages be used? How was Elixir created and what does it have in common with Erlang?

    Top Elixir Learning Media & Resources in 2022

    Regardless of whether you've only just heard of the Elixir programming language and would like to learn it, or if you're a seasoned developer with years of experience, you need adequate learning resources to ensure steady progress in your career - and just equally as important is the need to be up to date with what's new & trending in the functional