Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir alias on a submodule

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

I should be able to have this code working:

defmodule A do
  alias A.B, as: C

  defmodule B do
    defstruct name: ""
  end
end

iex(1)> %C{}

But instead i'm having this error:

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

Any idea of what i'm missing here ?

Edit: Module naming is simplified here for the exemple

like image 215
C404 Avatar asked Feb 09 '23 09:02

C404


1 Answers

This works only for the module in which the alias is defined, e.g.:

defmodule A do
  alias A.B, as: C

  defmodule B do
    defstruct name: ""
  end

  def new do
    %C{}
  end
end

You could then do:

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

This will also work in iex if you type the alias there:

iex(7)> alias A.B, as: C
nil
iex(8)> %C{}
%A.B{name: ""}
like image 64
Gazler Avatar answered Feb 15 '23 23:02

Gazler