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
:
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:
Way #2: Pattern matching using map synatx:
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:
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.