Using __MODULE__ in nested modules

If I have nested modules is it possible to use the syntax __MODULE__ in the submodule? I’m getting an error that says “cannot access struct RootModule …” when I have something like this:

defmodule RootModule do 
  defmodule SubModule do 
    defstruct [:foo, :bar]
    
    @spec new() :: %__MODULE__{}
    def new() do 
      %__MODULE__{}
    end 
  end
end

defstruct, not struct. =D

2 Likes

Sorry, that was just a typo here. In the actual code it was defstruct.

works for me, with defstruct.

1 Like

https://asciinema.org/a/llBek4Rb1JyX89lLTS4rErzoh

2 Likes

ah criminy. different typo. I had inserted a wayward end somewhere above the function definition so the submodule was “closed” and the function was being defined in the root module. derp.

1 Like

Works for me:

$ iex
Erlang/OTP 22 [erts-10.7] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe]

Interactive Elixir (1.10.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> defmodule RootModule do 
...(1)>   defmodule SubModule do 
...(1)>     defstruct [:foo, :bar]
...(1)>     
...(1)>     @spec new() :: %__MODULE__{}
...(1)>     def new() do 
...(1)>       %__MODULE__{}
...(1)>     end 
...(1)>   end
...(1)> end
iex(2)> RootModule.SubModule.new
%RootModule.SubModule{bar: nil, foo: nil}

What versions of erlang and elixir are you using?

sorry see above re: typo. Thanks for helping.