I know its possible to create a struct via %User{ email: 'blah@blah.com' }
. But if I had a variable params = %{email: 'blah@blah.com'}
is there a way to create that struct using that variable for eg, %User{ params }
.
This gives an error, just wondering if you can explode it or some other way?
The previous answers are both good, with one caveat: The keys in the struct are atoms, the keys in your hash might be strings. Using the struct() method will only copy over the keys that match, and strings won't match to the atoms. Example:
Using merge is odd, too, because it will "undo" the struct nature of the Map:
Found this on the elixir-lang-talk Google Group, from Jose himself:
https://groups.google.com/d/msg/elixir-lang-talk/6geXOLUeIpI/L9einu4EEAAJ
Another way of doing it using
Map.merge/2
:Example:
You should use the
struct/2
function. From the docs: