How does protocol dispatch work?

The module String.Chars has a function of to_string, and the kernel to_string just calls String.Chars.to_string.

What a protocol does it auto-generate the protocol functions from a list of definitions. So when you defimpl String.Chars, for: MyMod or whatever the syntax was then it defines a module, and at protocol consolidation time it scans all the compiled modules to see what is impl’d (just an attribute marker is all it is, of protocol_impl, so for your example it would have an attribute on the module of protocol_impl: [protocol: String.Char, for: MyMod]), and it uses those to build functions that just test, so in your example it would generate a function of:

defmodule String.Chars do
  # ... other stuff
  def to_string(%MyMod{}=v), do: String.Chars.MyMod.to_string(v)
  # ... other stuff
end

I have an enhanced Protocol library that you can see the code of how it works if curious too. Can also look at the elixir code as well. :slight_smile:

2 Likes