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?