Sweezy Zhao
Sweezy Zhao

Reputation: 11

how to use a struct in another module

I have used import User which is the struct module, but it still have error when I run a test code.

tried using use User and import User

defmodule User do
  @enforce_keys [:username, :password]
  defstruct [:username, :password]
end

In another module file

import User

newUser = %User{username: username, password: hashpass}


== Compilation error in file lib/user_store.ex ==
** (CompileError) lib/user_store.ex:84: User.__struct__/1 is undefined, cannot expand struct User
    (stdlib) lists.erl:1354: :lists.mapfoldl/3
    (elixir) expanding macro: Kernel.if/2

Upvotes: 1

Views: 1663

Answers (1)

Harrison Lucas
Harrison Lucas

Reputation: 2961

Since a struct is simply defined via a module, you don't need any special syntax to use/require/import the struct into another module and can just be referenced by its module name, surrounded by %_{}

So in your case:

#lib/user.ex
defmodule User do
  defstruct [:name]
end

#lib/app.ex
#...
%User{name: "Bobby Tables"}

Will work just fine.

If you are receiving an error saying that User.__struct__/1 is undefined - then this is a seperate issue which means that the current running beam process cannot find that module OR it wasn't compiled with that module.

Two Solutions:

  1. You aren't using the correct module name. Make sure you are using the full namespaced module name. e.g. if your struct is under defmodule My.App.User then when you use, you either need to say %My.App.User{} or alias My.App.User then %User{}

  2. You aren't compiling both files together. To Test this out, run iex then inside iex run c "path/to/struct_file" then %User{}. If that works, then it means in your project you aren't compiling the user struct file with the module where you are using it. If you have created a mix project then make sure you are starting your code with iex -S mix (if you are trying to run an interactive terminal) and all your modules live within /lib (or what's defined within your mix config file under elixirc_path

Upvotes: 3

Related Questions