Reputation: 1139
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?
Upvotes: 1
Views: 193
Reputation: 23586
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.
Upvotes: 3