# How does protocol dispatch work?

**URL:** <https://forum.elixirforum.com/t/how-does-protocol-dispatch-work/8114>\
**Category:** Discussions\
**Created:** [August 25, 2017, 4:00pm UTC](https://forum.elixirforum.com/t/how-does-protocol-dispatch-work/8114 "2017-08-25T16:00:10Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![NobbZ](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/nobbz/32/27235_2.png) [@NobbZ](https://forum.elixirforum.com/u/NobbZ)\
**Post date:** [August 25, 2017, 4:12pm UTC](https://forum.elixirforum.com/t/how-does-protocol-dispatch-work/8114/3 "2017-08-25T16:12:43Z")

</div>

This does only explain it roughly, but should be just enough to understand it.

1. `Kernel.to_string/1` is a macro, expanding to `String.Chars.to_string/1`
2. `String.Chars.to_string/1` matches on its argument, and without protocol consolidation it dispatches to `String.Chars.xxx.to_string/1` where `xxx` is the qualified alias of the struct or elixirs internal type. With consolidation those `xxx` implementations are integrated directly into `String.Chars.to_string/1`.

With consolidation it might look like this (simplified):

```elixir
defmodule String.Chars do
  def to_string(list) when is_list(list), do: List.to_string(list)
  def to_string(%Foo{bar: bar}), do: "#Foo<bar: #{bar}>"
end

```

without consilidation more like this:

```elixir
defmodule String.Chars do
  def to_string(list) when is_list(list), do: List.to_string(list)
  def to_string(%struct{} = item), do: :"Elixir.#{ __MODULE__ }.#{struct}" |> apply(:to_string, [item])
end

```

---

_[View the full topic](https://forum.elixirforum.com/t/how-does-protocol-dispatch-work/8114)._
