1

Structs are extensions built on top of maps. However, I was expecting the struct definition to be like,

defmodule User do
  defstruct %{name: "John", age: 27}
end

However, I was surprised find that the fields need to be defined as Keyword Lists.

defmodule User do
  defstruct [name: "John", age: 27]
end

I find this odd, is there a reason for this notation?

1 Answer 1

3

Because it allows you to use 2 different notations:

defstruct [:name, :age]

if there is no default value or:

defstruct [name: "John", age: 27]

if there are default values. You can even mix these two:

defstruct [:name, age: 27]

Additional if you use keyword list you can omit [] which is sometimes handy.

Sign up to request clarification or add additional context in comments.

1 Comment

I see, so it looks like it is purely for syntactic sugar. I also just found out that you can do this when declaring maps: ` %{name: "John", name: "Jose", age: 27}`

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.