[英]Elixir: Cannot access struct
I'm trying to get structs to work but none of the documented examples on the Internet or printed books work. 我正试图让结构工作,但互联网或印刷书籍上没有任何记录的例子。
This example on the web site ( https://www.tutorialspoint.com/elixir/elixir_structs.htm ) also shows the same problem: 网站上的这个例子( https://www.tutorialspoint.com/elixir/elixir_structs.htm )也显示了同样的问题:
defmodule User do
defstruct name: "John", age: 27
end
john = %User{}
#To access name and age of John,
IO.puts(john.name)
IO.puts(john.age)
I get the error cannot access struct User, the struct was not yet defined or the struct is being accessed in the same context that defines it. 我得到错误无法访问struct User,结构尚未定义或结构正在定义它的相同上下文中访问。
You're probably trying to run this using elixir <filename.exs>
while the book you may have seen similar code in was most likely typing the code into iex
. 您可能正在尝试使用
elixir <filename.exs>
来运行它,而您可能已经看过类似代码的书很可能是将代码输入到iex
。 (Edit: the code on the page you linked to has been lifted straight from the official tutorial ( http://elixir-lang.org/getting-started/structs.html ) which is typing that code into iex
). (编辑:您链接到的页面上的代码已直接从官方教程( http://elixir-lang.org/getting-started/structs.html )中提取,该教程正在将该代码键入
iex
)。 This will work in iex
but not in an exs
script; 这将在
iex
中iex
但不适用于exs
脚本; this is a limitation of the way Elixir "scripts" are compiled and evaluated. 这是对Elixir“脚本”编译和评估方式的限制。
I usually wrap the code in another function (and possibly another module) and invoke that at the end when I have to create and use structs in exs
scripts: 我通常将代码包装在另一个函数(可能还有另一个模块)中,并在我必须在
exs
脚本中创建和使用结构时调用它:
$ cat a.exs
defmodule User do
defstruct name: "John", age: 27
end
defmodule Main do
def main do
john = %User{}
IO.puts(john.name)
IO.puts(john.age)
end
end
Main.main
$ elixir a.exs
John
27
Wrapping struct creation and other related operations in a module should be sufficient. 在模块中包装结构创建和其他相关操作应该足够了。
defmodule Customer do
defstruct name: "", company: ""
end
defmodule BugReport do
defstruct owner: %Customer{}, details: "", severity: 1
end
defmodule Playground do
report = %BugReport{owner: %Customer{name: "X", company: "X"}}
IO.inspect report
end
$ elixir ./your_filename.ex $ elixir ./your_filename.ex
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.