Protocols in Elixir
In Elixir, a protocol is a set of functions that several types implement in their own way. The caller writes one name, such as size/1, and the runtime picks the implementation that belongs to the value it was given. It is how Enum works over lists and maps, how String.Chars turns values into text, and how a library adds behaviour to a type it does not own.
defprotocol declares the contract
defprotocol lists the functions with their arities and no bodies. The declaration is the contract; a type that implements it supplies the body. The protocol below promises one function, size/1, for any value that can answer "how big are you":
sized.exs
defprotocol Sized do def size(value) end defimpl Sized, for: List do def size(list), do: length(list) end defimpl Sized, for: BitString do def size(text), do: String.length(text) end IO.puts(Sized.size([1, 2, 3])) IO.puts(Sized.size("hello"))
elixir sized.exs
3
5
The two implementations are separate: the list one counts elements and the binary one counts characters, and neither knows about the other. A protocol is not an interface that a type declares; the implementation names the protocol and the type, so a library can implement a protocol for a type that lives in another library, as long as the protocol allows it.
One implementation per type
defimpl takes the protocol and a for: type. The type is the run-time type of the value: List, BitString, Integer, Map, or the name of a struct. Inside the block the functions are ordinary: they take the value and return the result:
- for: List covers every list, and the implementation receives the list.
- for: BitString covers binaries and bitstrings.
- for: Map covers plain maps; a struct needs its own implementation, because a struct is a type of its own.
- for: Any is the fallback, used only when the protocol sets @fallback_to_any true.
The dispatch section shows the fallback in action. Every other type needs its own block, which is why a protocol with three implementations is three defimpl blocks and one defprotocol.
Derive a stock implementation
Writing a full implementation for a simple struct is busywork, so some protocols ship a derivation. The @derive attribute on the struct asks the compiler to write the standard implementation, with options for the details:
derive.exs
defmodule Point do @derive {Inspect, only: [:x]} defstruct [:x, :y] end IO.inspect(struct(Point, %{x: 1, y: 2}))
elixir derive.exs
#Point<x: 1, ...>
The derived Inspect shows x and hides the rest of the struct, which keeps a log line short. Inspect and String.Chars are the everyday derivations; the standard library protocols lesson shows the rest and how IO.inspect reaches the implementation.
Dispatch at run time
The call Sized.size(value) looks at the type of the value at run time and calls the implementation for that type. The caller writes one name, and a list and a binary take different paths through the same line. A fallback for Any catches the types that have no implementation of their own:
any.exs
defprotocol Sized do @fallback_to_any true def size(value) end defimpl Sized, for: Any do def size(_value), do: :unknown end IO.puts(Sized.size(%{a: 1}))
elixir any.exs
unknown
A map has no Sized implementation, so the Any fallback answers. Without the fallback the same call raises the error of the next section. The fallback is a choice: a protocol that must support every value sets it, and a protocol that should fail loudly for an unknown type leaves it out.
The mistake: a type with no implementation
A protocol call on a type that has no implementation and no fallback raises Protocol.UndefinedError. The message names the protocol and the type, and the report shows the value it received:
noimpl.exs
defprotocol Sized do def size(value) end defimpl Sized, for: List do def size(list), do: length(list) end IO.puts(Sized.size(42))
elixir noimpl.exs
** (Protocol.UndefinedError) protocol Sized not implemented for Integer
Got value:
42
noimpl.exs:1: Sized.impl_for!/1
noimpl.exs:2: Sized.size/1
noimpl.exs:9: (file)
An integer is not a list, and no block implements Sized for it. The fix is the implementation for Integer, or a fallback for Any when every type should have an answer. The error is deliberate: a protocol that quietly returned nil for an unknown type would hide the missing implementation until the nil reached a place that could not use it.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a protocol declare?
Answer
A set of functions that several types implement in their own way
The protocol is the contract; each type supplies its own defimpl.
-
What does
defimpl Sized, for: Listmean?Answer
The functions of Sized for values that are lists
The for: option names the run-time type the implementation belongs to.
-
How does a protocol choose an implementation?
Answer
By the run-time type of the value it is given
Dispatch reads the type of the value, which is why a list and a binary take different blocks.
-
What does
@derive {Inspect, only: [:x]}do?Answer
It asks the compiler to write an Inspect implementation that shows only x
A derivation writes a stock implementation, and the options narrow what it shows.
-
What does this program print?
defprotocol Sized do def size(value) end defimpl Sized, for: List do def size(list), do: length(list) end IO.puts(Sized.size([1, 2]))Answer
2
The list implementation counts the elements, and the list has two.
-
What does this program print?
defprotocol Sized do def size(value) end defimpl Sized, for: BitString do def size(text), do: String.length(text) end IO.puts(Sized.size("abc"))Answer
3
The binary implementation counts characters, and the string has three.
-
What does this program print?
defmodule Point do @derive {Inspect, only: [:x]} defstruct [:x, :y] end IO.inspect(struct(Point, %{x: 1, y: 2}))Answer
#Point<x: 1, ...>
The derived implementation shows x and hides the other fields behind the dots.
-
What does this program print?
defprotocol Sized do @fallback_to_any true def size(value) end defimpl Sized, for: Any do def size(_value), do: :unknown end IO.puts(Sized.size(%{a: 1}))Answer
unknown
A map has no implementation, so the Any fallback answers.
-
What does this program do?
defprotocol Sized do def size(value) end IO.puts(Sized.size(42))Answer
A Protocol.UndefinedError, because Integer has no implementation
Without a block for Integer or Any, the protocol has nothing to call.
-
When is an
Anyimplementation used?Answer
When the protocol sets @fallback_to_any true and the type has no block of its own
The fallback is opt-in and catches the types without a specific implementation.
Автор статьи: Arthur Isaev