If structs are just maps underneath then how does pattern matching to ensure struct type work?
For example:
defmodule Attendee do
defstruct name: "", paid: false, over_18: true
def may_attend_after_party(attendee = %Attendee{}) do
attendee.paid && attendee.over_18
end
def may_attend_after_party_without_struct(attendee = %{name: "", paid: false, over_18: true}) do
attendee.paid && attendee.over_18
end
end
iex(1)> Attendee.may_attend_after_party(%Attendee{name: "John"})
false
iex(2)> Attendee.may_attend_after_party(%Attendee{name: "John", paid: true})
true
iex(3)> Attendee.may_attend_after_party_without_struct(%Attendee{name: "John", paid: true})
** (FunctionClauseError) no function clause matching in Attendee.may_attend_after_party_without_struct/1
The following arguments were given to Attendee.may_attend_after_party_without_struct/1:
# 1
%Attendee{name: "John", over_18: true, paid: true}
structwtf.exs:8: Attendee.may_attend_after_party_without_struct/1
iex(4)>
%Attendee{}
evaluates to %Attendee{name: "", over_18: true, paid: false}
, and if structs are just maps underneath, then shouldn’t the behaviour remain similar?