如何在灵药中使用defdelegate?

Bal*_*ala 8 elixir

有人可以提供一个简单的例子defdelegate.我找不到任何东西,让人难以理解.

defmodule Dummy do
  def hello, do: "hello from dummy"
end
Run Code Online (Sandbox Code Playgroud)

我得到undefined function world/0以下内容:

defmodule Other do
  defdelegate hello, to: Dummy, as: world
end
Run Code Online (Sandbox Code Playgroud)

我想委托Other.worldDummy.hello

Dog*_*ert 21

两件事情:

  1. 你得到了名字和as:错误.as:应包含目标模块中函数的名称,第一个参数应该是当前模块中要定义的名称.

  2. as需要成为原子的论据.

最终工作代码:

defmodule Dummy do
  def hello, do: "hello from dummy"
end

defmodule Other do
  defdelegate world, to: Dummy, as: :hello
end

IO.puts Other.world
Run Code Online (Sandbox Code Playgroud)

输出:

hello from dummy
Run Code Online (Sandbox Code Playgroud)

  • @JuzerAli,你没有。私有方法只能在模块内使用,因此如果您觉得需要委托给私有方法,那么您的设计就有缺陷。 (2认同)