Type safety with Structs in Elixir

This article assumes you are familiar with maps in Elixir, if not, take a look at this article for a brief on maps.

Ok with that out of the way what are Structs?

Structs are extensions built on maps that provide two things;

  1. Compile time checks — Structs provide compile-time guarantees that only the fields (and all of them) defined in a struct will exist.
  2. Default values — When defining structs it is possible to provide default values for fields if a value isn’t defined nil will be assumed.

Let’s take a look at some some code

defmodule Application.Person do 
defstruct first_name: "", second_name: "" age: nil, height: ""

Structs assume the name of the module they are defined in and a module can only contain one struct.

Here we can see we are using the defstruct macro in the Person module to define a struct with 4 fields (first_name, second_name, age, height)

Now to use a struct we would have to import the module and declare a new instance of it

Here we see we alias Application.Person to Person using a short hand and the first time we use it is in a pattern match.

%Person{} = person

Here what we are doing is using pattern matching to ensure that we receive a struct of type person in our function.

Boom! Type Safety 💣

But wait there is more…

Structs can contain functions that are often needed by the users of the structs. Say for our struct we needed to get the full name of a user we could add a function to our struct for this.

Above you see we added a full name function to our person struct now if we added a function to print our users name all we would do is

def print_name(%Person{} = person) do 
IO.puts Person.fullname(person)

This would log out the joined first and last name of our Person struct.

Using structs we can ensure type safety for the data that passes through our application.

Bonus … Protocols and Structs are the backbone of polymorphism in Elixir

With this I hope you can go forth and struct!

Any questions? Suggestions ?

Leave a comment

Back to code 😝