Does the module generated by the implementation protocol have other practical significance?

I accidentally discovered that the __MODULE__ in the defimpl block is not the module name of struct, but a new one.

defmodule Foo do
  defstruct [:bar]

  defimpl String.Chars do
    def to_string(_foo) do
      "Foo module name: `#{__MODULE__}`"
    end
  end
end
iex> %Foo{} |> to_string
"Foo module name: `Elixir.String.Chars.Foo`" # Not what I expected, the name of the Foo module.

I want to know, besides making the polymorphism of the protocol work correctly, what other meanings does this new module have?

That is how protocols work. Module.concat(protocol, type_module), this is the module with the implementation of the protocol for a given type_module.

Beyond that, its just a module as any other.

4 Likes