Lets say I have a struct, lets say named Struct with the singular field x (default 0).
When I create it I get &Struct{x: 0}
Since they are maps I then use Map.put to add something else like y: 5 I get %{struct: S, x: 0, y: 5} and it is no longer an Stuct
Is there some way to purge any non struct fields and restore it to an Struct?
Two downsides to this approach compared to the previous:
This solution won’t replace any missing keys.
This approach doesn’t let you create the struct dynamically (not without wrapping it in struct/0 at least, which at that point you might as well do the other).
you can also use map cons, if you would like for your code to crash when you try to assign a nonexistent field, lets you catch errors in tests (how good is your test coverage? lol)
defmodule S do
defstruct [x: 0]
def do_something(val = %S{}) do
%{val | y: "oops"}
end
end
will crash on do_something. Whenever it’s a struct, I prefer using map cons for that bailout behaviour.