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

    Phoenix LiveView Tutorial: Adding Phoenix PubSub and Pow Authentication to Messenger

    We've already bootstrapped our Phoenix LiveView-based Messenger app's database structure and a first LiveView page.

    This time, we're going to improve real-time communication between the app's users using Phoenix PubSub, and use the Pow library to add secure user authentication.

    As of November 2020, the latest Phoenix LiveView version is 0.14.8 - and the series has been updated to match it!

    5 top-tier companies that use Elixir

    Elixir is a pretty capable language - and it consistently ranks near the top of most loved and wanted languages rankings. It has a large following and some very persuasive preachers as well. But that would not be enough to make me like it – what I need as real proof of its strengths is real businesses that strive with Elixir.

    That’s what this list is all about – a bunch of stories from top companies that chose Elixir and never looked back. Let us show you how its power and versatility shows in practice.