What is Struct versus Map in Elixir?

Share

Struct

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.

Map

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.

Pragmatic differences

The pragmatic differences between the definitions of the struct and map are as follows:

# defining the map
alpha_num = %{a: "1", b: "2", c: "3"}
# printing the map's key-value pair
IO.puts("Printing the Data of Map")
Enum.each alpha_num, fn {k, v} ->
IO.puts("#{k} --> #{v}")
end
#defining the struct
defmodule User do
defstruct name: "", gender: ""
end
# printing the struct using another module
IO.puts("Printing the the Data of Struct")
defmodule Run do
alex = %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.

When to use structs?

It’s safe to use structs when:

  • We know all the keys ahead of time.

  • We want to achieve data polymorphismInvoking a function depending on the struct’s type..

Why not maps?

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:

  • Fields are known upfront.
  • Keys can be atoms.
  • Sensible defaults exist.

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.

Copyright ©2024 Educative, Inc. All rights reserved