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

最后都变了- 提交于 2019-11-27 13:23:50
José Valim

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"}

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:

defmodule User do
  defstruct name: "john"
end

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

Using merge is odd, too, because it will "undo" the struct nature of the Map:

user = Map.merge(%User{}, opts)
#=> %{:__struct__ => User, :name => "john", "name" => "meg"}

Found this on the elixir-lang-talk Google Group, from Jose himself:

https://groups.google.com/d/msg/elixir-lang-talk/6geXOLUeIpI/L9einu4EEAAJ

That's pretty much the way to go except you can do everything in one pass:

def to_struct(kind, attrs) do
  struct = struct(kind)
  Enum.reduce Map.to_list(struct), struct, fn {k, _}, acc ->
    case Map.fetch(attrs, Atom.to_string(k)) do
      {:ok, v} -> %{acc | k => v}
      :error -> acc
    end
  end
end

Another way of doing it using Map.merge/2:

merge(map1, map2)

Example:

params
#=> %{email: "blah@blah.com"}

%User{} |> Map.merge(params)
#=> %User{ email: 'blah@blah.com' }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!