I cannot import(alias) defstruct

I’m learning Pheonix via programming Pheonix > 1.4 book. The chapter 3 code cannot run.

defmodule Rumbl.Accounts.User do
  defstruct [:id, :name, :username]
end

defmodule Rumbl.Accounts do

  alias Rumbl.Accounts.User

  def list_users do
    [
      %User{id: "1", name: "jose", username: "josevalim"}
    ]
  end
end

Then run in iex. I faced this error.

** (CompileError) accounts.ex:7: Rumbl.Accounts.User.__struct__/1 is undefined, cannot expand struct Rumbl.Accounts.User. Make sure the struct name is correct. If the struct name exists and is correct 
but it still cannot be found, you likely have cyclic module usage in your code

image

What am I wrong?

1 Like

Maybe you should try iex -S mix instead of just iex.

1 Like
Erlang/OTP 25 [erts-13.0.4] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]

** (Mix) "mix" with no arguments must be executed in a directory with a mix.exs file

Now I can see this error. How can I solve this?

oops. this is my mistake. I move the root path. it running well.
what is different iex -S mix and mix phx.server ?

I still suffering from this error.
I tried iex -S accounts.ex but It shows the same error.

** (CompileError) accounts.ex:10: Rumbl.Accounts.User.__struct__/1 is undefined, cannot expand struct Rumbl.Accounts.User. Make sure the struct name is correct. If the struct name exists and is correct but it still cannot be found, you likely have cyclic module usage in your code

I don’t know what it is. Why elixir cannot find the Rumbl.Accounts.User.

Sorry for being late to reply. I’m in China so I was sleeping when you asked the question.

iex -S mix starts an iex session with all the .ex files in the elixirc paths compiled and loaded (including the .ex files in the dependencies of your project), all the “applications” of your project started, and all the supervision trees built. But, as for a phoenix project, iex -S mix does not start the web server.

mix phx.server also compiles all the .ex files, starts, all the applications, and builds all the supervision trees. It also starts the web server, but it does not start an iex session.

If you want both, you can try iex -S mix phx.server.

There is no iex -S your_module.ex. You can start an mix-aware iex session by iex -S mix, and in that session, do whatever you want with your modules. Or, you can type mix eval '<your code>'.

3 Likes

Thank you. I solved this problem.