What is the difference between these two module definitions?

时间:2015-11-12 12:09:52

标签: elixir phoenix-framework

Regarding the Phoenix Framework: I was just wondering what the difference is between writing

defmodule MyApp.User do
  # some code
end

and just

defmodule User do
  # some code
end

later on it would be easier to just write User.function than MyApp.User.function

2 个答案:

答案 0 :(得分:6)

这是命名空间模块以避免冲突。想象一下,您可以调用模块User,然后使用名为user的库,该库也定义了User模块。你会发生碰撞。

您可以在使用User模块的模块中alias

defmodule MyApp.SomeModule do
  alias MyApp.User

  def foo do
    User.some_function
  end
end

答案 1 :(得分:1)

它可以在elixir中应用nesting的概念。通常,您希望根据功能对某些模块进行分组,或者只是为了命名一致性。 以下是文档中的直接示例

defmodule Foo do
  defmodule Bar do
  end
end

相同
defmodule Elixir.Foo do
  defmodule Elixir.Foo.Bar do
  end
  alias Elixir.Foo.Bar, as: Bar
end

值得注意的是,在Elixir中,无需定义外部模块即可使用Outer.Inner模块名称,因为语言会将所有模块名称转换为原子。您可以定义任意嵌套的模块,而无需在链中定义任何模块(例如,Foo.Bar.Baz,而不首先定义Foo或Foo.Bar)。

elixir docs提供了一个可靠的示例。

相关问题