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:
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.
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
. (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
). This will work in iex
but not in an exs
script; this is a limitation of the way Elixir "scripts" are compiled and evaluated.
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:
$ 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With