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!
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
You might also like
Discover more content from this category
Did you know that it's possible to set default value in Javascript object destructuring?
Each of us had a situation, where we had to invoke a few, same commands each time. Making it once is not that problematic, but when we are supposed to repeat given operations, it may be better just to create one function that will handle it all.
It's easy to contain absolute positioned elements. Things get a little trickier when you want to contain a fixed positioned element without changing its stylings.
