Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir: Cannot access struct

Tags:

struct

elixir

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.

like image 499
iphaaw Avatar asked Sep 19 '16 14:09

iphaaw


2 Answers

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
like image 176
Dogbert Avatar answered Sep 22 '22 18:09

Dogbert


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

like image 41
Aleks Tkachenko Avatar answered Sep 21 '22 18:09

Aleks Tkachenko