如何在另一个模块中使用struct

问题描述 投票:0回答:1

我使用了作为struct模块的import User,但是当我运行测试代码时它仍然有错误。

尝试使用use Userimport 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
elixir
1个回答
1
投票

由于结构只是通过模块定义,因此您不需要任何特殊语法来使用/ require / import结构到另一个模块中,并且可以通过其模块名称引用,由%_{}包围

所以在你的情况下:

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

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

会工作得很好。

如果您收到错误,指出User.__struct__/1未定义 - 那么这是一个单独的问题,这意味着当前运行的梁流程无法找到该模块,或者它未使用该模块进行编译。

两种方案:

  1. 您没有使用正确的模块名称。确保使用完整的命名空间模块名称。例如如果您的结构在defmodule My.App.User下,那么当您使用时,您需要说%My.App.User{}alias My.App.User然后%User{}
  2. 您没有一起编译这两个文件。要测试这个,运行iex然后在iex运行c "path/to/struct_file"然后%User{}。如果可行,则表示您在项目中没有使用您正在使用它的模块编译用户结构文件。如果您已创建混合项目,请确保使用iex -S mix启动代码(如果您尝试运行交互式终端)并且所有模块都位于/lib内(或者在elixirc_path下的mix配置文件中定义的内容)
© www.soinside.com 2019 - 2024. All rights reserved.