john
john

Reputation: 1075

Elixir: def structs with fields as lists of another struct type

If I have the following struct:

defmodule Events.InviteEvent do
  defstruct [
    :event_id,
    :invite_list
  ]
end

Is it possible to define the :invite_list to be a list of which has a type of another struct ? Basically I would like to define a struct with the following structure:

{
event_id: 123,
invite_list: [
              {name: "jason", email: "[email protected]"},
              {name: "judy", email: "[email protected]"}
              ]
}

Upvotes: 2

Views: 1689

Answers (2)

mkumm
mkumm

Reputation: 1

In practice, I often add lists to my struct. So assuming you had an %Invite{} struct, I would write something like the following:

defmodule Events.InviteEvent do

  defstruct [
    event_id: nil,
    invite_list: []
  ]

end

Then populate as you want.

%Events.InviteEvent{
  event_id: 123, 
  invite_list: [
    %Invite{name: "jason", email: "[email protected]"}, 
    %Invite{name: "judy", email: "[email protected]"}
  ]

If you need to be careful that invite_list only contains a list of %Invite{}, then manage that with the interface to your struct.

Upvotes: 0

Adam Millerchip
Adam Millerchip

Reputation: 23091

From Structs:

Structs provide compile-time guarantees that only the fields (and all of them) defined through defstruct will be allowed to exist in a struct

The only guarantee you get is that the field names are present. There is no way to specify the type of the values.

You could write a helper function to build your struct that uses typespecs, but that doesn't give you any extra compile-time or run-time guarantees.

Upvotes: 3

Related Questions