Protocols and Structs

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

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

protocols/basic.exs
 
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 for all the world as if we’ve created some new type, the blob. But 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 ...

Get Programming Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.