elixir

Load values into a Struct from a Map in Elixir


Let's say I've a map with some user data:

iex(1)> user_map
#=> %{name: "Some User", email: "user@example.com", password: "*********"}

How can I load this into a %User{} struct (hopefully using some Rubyish Elixir Magic)?


I've currently tried these but all of them failed. Going through the Structs section on Elixir website.

user_struct = %{ %User{} | user_map }
user_struct = %{ %User{} | Enum.to_list(user_map) }

Solution

  • Found the answer on the elixir-lang-talk mailing list. We can use the struct/2 method:

    struct(User, user_map)
    #=> %User{name: "Some User", email: "user@example.com", password: "*********"}
    

    Another way, as mentioned by Dogbert, is to use Map.merge/2:

    Map.merge(%User{}, user_map)
    #=> %User{name: "Some User", email: "user@example.com", password: "*********"}
    

    Note: Map.merge/2 cannot handle enforced keys on structs, so it is not recommended for structs