我使用了作为struct模块的import User,但是当我运行测试代码时它仍然有错误。
尝试使用use User
和import User
defmodule User do
@enforce_keys [:username, :password]
defstruct [:username, :password]
end
在另一个模块文件中
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
由于结构只是通过模块定义,因此您不需要任何特殊语法来使用/ require / import结构到另一个模块中,并且可以通过其模块名称引用,由%_{}
包围
所以在你的情况下:
#lib/user.ex
defmodule User do
defstruct [:name]
end
#lib/app.ex
#...
%User{name: "Bobby Tables"}
会工作得很好。
如果您收到错误,指出User.__struct__/1
未定义 - 那么这是一个单独的问题,这意味着当前运行的梁流程无法找到该模块,或者它未使用该模块进行编译。
两种方案:
defmodule My.App.User
下,那么当您使用时,您需要说%My.App.User{}
或alias My.App.User
然后%User{}
iex
然后在iex运行c "path/to/struct_file"
然后%User{}
。如果可行,则表示您在项目中没有使用您正在使用它的模块编译用户结构文件。如果您已创建混合项目,请确保使用iex -S mix
启动代码(如果您尝试运行交互式终端)并且所有模块都位于/lib
内(或者在elixirc_path
下的mix配置文件中定义的内容)