Elixir Structs

Welcome to a tutorial on Struct in Elixir.

In Elixir, Structs are extensions built on top of maps that provide compile-time checks and default values.

 

Defining Structs

To define a struct, the defstruct construct is used like this:

defmodule User do
   defstruct name: "John", age: 29
end

In the above code, the keyword list used with defstruct defines what fields the struct will have along with their default values. Also, Structs take the name of the module they are defined in. from the above example, we defined a struct named User, also, we can create User structs by making use of a syntax similar to the one used to create maps. Check out the code below.

new_john = %User{})
ayush = %User{name: "Alex", age: 23}
megan = %User{name: "Justin"})

The above code will generate three different structs with values, as shown below:

%User{age: 29, name: "John"}
%User{age: 23, name: "Alex"}
%User{age: 29, name: "Justin"}

More importantly, Structs provide compile-time guarantees that only the fields (and all of them) defined through defstruct will be allowed to exist in a struct. Hence, you cannot define your own fields once you have created the struct in the module.

 

Accessing and Updating Structs

In the tutorial on maps, we showed how we can access and update the fields of a map. The same techniques and the same syntax apply to structs as well. Check out the example where we want to update the user we created in the earlier example, then:

defmodule User do
   defstruct name: "John", age: 29
end
john = %User{}
#john right now is: %User{age: 29, name: "John"}

#To access name and age of John, 
IO.puts(john.name)
IO.puts(john.age)

The output is:

John
29

Now, to update a value in a struct, we will use the same procedure that we used in the map tutorial. This is shown below.

meg = %{john | name: "Meg"}

Structs can also be used in pattern matching, both for matching the value of specific keys as well as for ensuring that the matching value is a struct of the same type as the matched value.