Elixir Pattern Matching Struct And Map

I started learning Elixir recently, while working on a personal project I had to pattern match between struct and map in a function. While glancing through the documentation I came across a function is_map, as the name suggests it check if the argument is map or not. Coming from a C# background I thought it is going to work, but it didn’t.

In Elixir struct is a special kind of map, so is_map function matches both. Then I went through some of the open source code bases and came across a way to do this(don’t remember from which project I saw this)

1
2
3
4
5
6
7
8
9
# This match struct
def clean_up(data = %_{}) do
.....
end

# This match map
def clean_up(data = %{}) do
....
end

Very powerful pattern matching technique and elegant solution. Here if data is a struct it matches first function and if it is map matches the second one.