O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required