Elixir 協議介紹

協議使 Elixir 中的多型性成為可能。使用 defprotocol 定義協議:

defprotocol Log do
  def log(value, opts)
end

使用 defimpl 實現協議:

require Logger
# User and Post are custom structs

defimpl Log, for: User do
  def log(user, _opts) do
    Logger.info "User: #{user.name}, #{user.age}"
  end
end

defimpl Log, for: Post do
  def log(user, _opts) do
    Logger.info "Post: #{post.title}, #{post.category}"
  end
end

通過上面的實現,我們可以做到:

iex> Log.log(%User{name: "Yos", age: 23})
22:53:11.604 [info]  User: Yos, 23
iex> Log.log(%Post{title: "Protocols", category: "Protocols"})
22:53:43.604 [info]  Post: Protocols, Protocols

協議允許你分派到任何資料型別,只要它實現協議。這包括一些內建型別,如 AtomBitStringTuples 等。