子模块上的 Elixir 别名

Elixir alias on a submodule

根据http://elixir-lang.org/getting-started/alias-require-and-import.html#aliases

我应该能够让这段代码工作:

defmodule A do
  alias A.B, as: C

  defmodule B do
    defstruct name: ""
  end
end

iex(1)> %C{}

但是我遇到了这个错误:

** (CompileError) iex:1: C.__struct__/0 is undefined, cannot expand struct C

知道我在这里遗漏了什么吗?

编辑: 此处简化模块命名示例

这仅适用于定义别名的模块,例如:

defmodule A do
  alias A.B, as: C

  defmodule B do
    defstruct name: ""
  end

  def new do
    %C{}
  end
end

然后你可以这样做:

iex(6)> A.new
%A.B{name: ""}

如果你在那里输入别名,这也适用于 iex:

iex(7)> alias A.B, as: C
nil
iex(8)> %C{}
%A.B{name: ""}