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
协议允许你分派到任何数据类型,只要它实现协议。这包括一些内置类型,如 Atom
,BitString
,Tuples
等。