Type safety with Structs in Elixir

Oct 24, 2017 · 2 min read

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.

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 😝

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store