Reputation: 1075
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
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
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