Elixir alias on submodule

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

I should have this code:

defmodule A do
  alias A.B, as: C

  defmodule B do
    defstruct name: ""
  end
end

iex(1)> %C{}

But instead, I have this error:

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

Any idea that I'm missing here?

Edit: Naming modules is simplified here for an example.

+4
source share
1 answer

This only works for the module in which the alias is defined, for example:

defmodule A do
  alias A.B, as: C

  defmodule B do
    defstruct name: ""
  end

  def new do
    %C{}
  end
end

Then you can:

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

This will also work in iex if you enter an alias there:

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

Source: https://habr.com/ru/post/1618700/


All Articles