3

I have this modules where I'm trying to define a struct:

defmodule A do
  defmodule B do
    defstruct :id, :name
  end
end

Why error?

undefined function defstruct/2

Why is this error?

2 Answers 2

5

Elixir interprets defstruct :id, :name as calling defstruct with 2 arguments, that's the /2 part in undefined function defstruct/2.

What you want to do is pass a single argument to defstruct, a list of field names:

defmodule A do
  defmodule B do
    defstruct [:id, :name]
  end
end
Sign up to request clarification or add additional context in comments.

Comments

4

Just check the official documentation in that matter.

You can use notation without square brackets, but you have be explicit and provide a keyword list. In example there are default values provided.

In your case :id, :name won't be keyword list and that's why compiler throw an error that you put there two arguments.

If you would do:

defmodule A do
  defstruct id: nil, name: nil
end

It would works perfectly fine.

Otherwise use explicitly list.

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.