Difference between protocol & behaviour in elixir

后端 未结 2 985
小鲜肉
小鲜肉 2020-12-29 19:55

Behaviours define callbacks & protocols define methods without signatures. Modules implementing a protocol should give definition for all those methods. Same for modules

相关标签:
2条回答
  • 2020-12-29 20:38

    Answered by José Valim on the same topic ( from google thread, https://groups.google.com/forum/#!msg/elixir-lang-talk/S0NlOoc4ThM/J2aD2hKrtuoJ )

    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.

    0 讨论(0)
  • 2020-12-29 20:51

    Protocol is type/data based polymorphism. When I call Enum.each(foo, ...), the concrete enumeration is determined from the type of foo.

    Behaviour is a typeless plug-in mechanism. When I call GenServer.start(MyModule), I explicitly pass MyModule as a plug-in, and the generic code from GenServer will call into this module when needed.

    0 讨论(0)
提交回复
热议问题