Structs are wrappers around maps that provide additional functionality to the maps.
Struct is a map under the hood with an additional field called __struct__
. Unlike map, when we create a struct, we can include specific fields or provide a default value to some fields. Keys in a struct must be atoms, whereas a map doesn’t support this capability.
A map is like a key-value pair. It is the go-to structure in Elixir. It cannot have duplicate keys, nor the order of keys is preserved. Maps do not restrict the key’s type: anything can be a key in a map.
The pragmatic differences between the definitions of the struct and map are as follows:
# defining the mapalpha_num = %{a: "1", b: "2", c: "3"}# printing the map's key-value pairIO.puts("Printing the Data of Map")Enum.each alpha_num, fn {k, v} ->IO.puts("#{k} --> #{v}")end#defining the structdefmodule User dodefstruct name: "", gender: ""end# printing the struct using another moduleIO.puts("Printing the the Data of Struct")defmodule Run doalex = %User{name: "Alex", gender: "Male"}john = %User{name: "John", gender: "Male"}megan = %User{name: "Megan", gender: "Female"}IO.puts("#{alex.name} --> #{alex.gender}")IO.puts("#{john.name} --> #{john.gender}")IO.puts("#{megan.name} --> #{megan.gender}")end
Note: We don’t create any module to define its values for the map,
alpha_num
in the code above. Whereas we have to create a module with the name of the struct:User
.
It’s safe to use structs when:
We know all the keys ahead of time.
We want to achieve
The following points indicate why it’s not best practice to use maps:
Maps allow any value as a key.
Maps’ keys do not obey any order.
Maps in Elixir are immutable.
Unlike structs, maps do not provide compile-time checks and default values.
Structs versus maps are a little more nuanced discussion. Structs have some requirements:
Even if all these hold, we may still use a map if the scope or lifetime of the structure is minimal. An example is a map that is only passed between 2 to 3 functions. When the scope or lifetime is larger (used in multiple modules), it makes more sense to define a struct.
Free Resources