Elixir - Structs



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 −

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

The keyword list used with defstruct defines what fields the struct will have along with their default values. Structs take the name of the module they are defined in. In the example given above, we defined a struct named User. We can now create User structs by using a syntax similar to the one used to create maps −

new_john = %User{})
ayush = %User{name: "Ayush", age: 20}
megan = %User{name: "Megan"})

The above code will generate three different structs with values −

%User{age: 27, name: "John"}
%User{age: 20, name: "Ayush"}
%User{age: 27, name: "Megan"}

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

Accessing and Updating Structs

When we discussed 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. For example, if we want to update the user we created in the earlier example, then −

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

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

When the above program is run, it produces the following result −

John
27

To update a value in a struct, we will again use the same procedure that we used in the map chapter,

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

Structs can also be used in pattern matching, both for matching on 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.

Advertisements