In Elixir how do you initialize a struct with a map variable

bullfrog picture bullfrog · Jun 19, 2015 · Viewed 20.3k times · Source

I know its possible to create a struct via %User{ email: '[email protected]' }. But if I had a variable params = %{email: '[email protected]'} 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?

Answer

José Valim picture José Valim · Jun 19, 2015

You should use the struct/2 function. From the docs:

defmodule User do
  defstruct name: "john"
end

struct(User)
#=> %User{name: "john"}

opts = [name: "meg"]
user = struct(User, opts)
#=> %User{name: "meg"}

struct(user, unknown: "value")
#=> %User{name: "meg"}