May 2018
Intermediate to advanced
412 pages
9h 3m
English
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:
| | 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 ... |
Read now
Unlock full access