Protocols and Structs

Understand the protocols and structs in Elixir.

We'll cover the following

Elixir doesn’t have classes, but perhaps surprisingly it does have user-defined types. It pulls this off using structs and a few conventions.

Example

Let’s play with a simple struct. Here’s the definition:

defmodule Blob do 
  defstruct content: nil
end

And here, we use it in IEx:

iex> c "basic.exs"
[Blob]
iex> b = %Blob{content: 123} 
%Blob{content: 123}
iex> inspect b
%Blob{content: 123}"

It looks as if we’ve created some new type, the Blob. That’s only because Elixir is hiding something from us. By default, inspect recognizes structs. If we turn this off using the structs: false option, inspect reveals the true nature of our Blob value:

iex> inspect b, structs: false 
"%{__struct__: Blob, content: 123}"

A struct value is actually just a map with the key __struct__ referencing the struct’s module (Blob in this case) and the remaining elements containing the keys and values for this instance. The inspect implementation for maps checks for this. If we ask it to inspect a map containing a key __struct__ that references a module, it displays it as a struct.

Many built-in types in Elixir are represented as structs internally. It’s instructive to try creating values and inspecting them with structs: false.

Run the commands given in the above snippets to execute the code below:

Get hands-on with 1200+ tech skills courses.