Loading values ​​into the structure from the map in the elixir

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

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

How can I load this into the %User{} structure (hopefully using some Rubyish Elixir magic)?


I have tried this for now, but they all failed. Go to the Structs section of the Elixir website.

 user_struct = %{ %User{} | user_map } user_struct = %{ %User{} | Enum.to_list(user_map) } 
+5
source share
1 answer

An answer was found 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 Dogbert mentioned, is to use Map.merge/2 :

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

All Articles