【问题标题】:Calling imported module functions directly in elixir在 elixir 中直接调用导入的模块函数
【发布时间】:2015-12-19 20:50:58
【问题描述】:

我刚刚开始学习 Elixir,但我无法弄清楚 Elixir 中的 import 是如何工作的。 当我使用 import 将一个模块导入另一个模块时,我无法使用导入它的模块来调用导入的函数。

但是我可以在导入模块的函数内部调用导入模块的函数。

defmodule A do
  def func do
   IO.puts("func called")
  end
end

defmodule B do
  import A
end

A.func # o/p: "func called"
B.func # (UndefinedFunctionError) undefined function: B.func/0

defmodule B do
  import A

  def func2 do
    func
  end
end

B.func2 # o/p "func called"

当我能够从func2 调用func 时,我无法弄清楚为什么B.func 不起作用。是否有某种我缺少的理论。来自 Ruby 背景的这种行为对我来说看起来很奇怪。请任何人帮助我或指出一些好的资源来阅读。

【问题讨论】:

    标签: import elixir


    【解决方案1】:

    import 并没有像许多其他语言那样真正导入任何东西。它所做的只是使导入模块的导出函数可以从当前命名空间访问。引用the docs

    当我们想要轻松访问来自其他模块的函数或宏而不使用完全限定名称时,我们会使用import

    如果你想让A.funcB.func 指向同一个函数,你有几个选择。第一个很简单——制作一个包装函数:

    defmodule B do
      def func do
         A.func
      end
    end
    

    如果您想要一些更复杂的继承类型的东西,您可以考虑使用defoverridablesuper 创建一个__using__

    【讨论】:

    • 感谢您的链接和详细解答
    • 另一种说法是 import 是词法的,这篇文章希望能澄清它:thepugautomatic.com/2015/11/elixir-scoping 另外,避免“类似继承”的东西,只鼓励回调。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    相关资源
    最近更新 更多