Elixir Protocols vs Behaviours

Table of Contents

1 Protocols & Behaviours 不同

A protocol is indeed a behaviour + dispatching logic.

However I think you are missing the point of behaviours. Behaviours are extremely useful. For example, a GenServer defines a behaviour. A behaviour is a way to say: give me a module as argument and I will invoke the following callbacks on it, which these argument and so on. A more complex example for behaviours besides a GenServer are the Ecto adapters.

However, this does not work if you have a data structure and you want to dispatch based on the data structure. Hence protocols.

by José Valim

Behaviours 的例子是 GenServer, 一个 GenServer 实现了不同的callback 供调用, Behaviours 描述了module需要提供哪些函数

Protocols 是基于类型/数据的多态, 比如 Enum.each(foo, ...) 具体怎么迭代由 foo 的类型决定


  • Behaviours 是由 erlang 提供的机制
  • Protocols 是Elixir 新加的机制

2 links

Author: lidashuang

Created: 2018-05-04 Fri 13:11

Emacs 25.3.3 (Org mode 8.2.10)