17

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.

2 Answers 2

36

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
Sign up to request clarification or add additional context in comments.

3 Comments

Can you clarify what exactly this "limitation" is? Does this only apply to .exs-files?
Why is import User not necessary in the module Main?
import keyword is not for being able to use modules in this language, it is for this: hexdocs.pm/elixir/main/alias-require-and-import.html
4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.