JustMichaelの答えに展開するには、あなたが最初にString.to_existing_atom/1
を使用して、原子にキーを変換することができ、Kernel.struct/2
:ドキュメントへ
defmodule TestStruct do
defstruct field_one: nil,
field_two: nil,
field_three: nil,
field_four: nil
use ExConstructor
end
TestStruct.new(%{"field_one" => "a", "fieldTwo" => "b", :field_three => "c", :FieldFour => "d"})
# => %TestStruct{field_one: "a", field_two: "b", field_three: "c", field_four: "d"}
はリンク:ここで小さな例です
:これはVMあちこちを防ぐためにString.to_existing_atom/1
を使用していることを
user_with_atom_keys = for {key, val} <- user, into: %{} do
{String.to_existing_atom(key), val}
end
user_struct = struct(UserInfo, user_with_atom_keys)
# %UserInfo{basic_auth: "Basic Ym1hOmphYnJhMTc=", firstname: "foo",
lastname: "boo"}
注意グローバルなAtom制限に達する。
http://stackoverflow.com/questions/30927635/in-elixir-how-do-you-initialize-a-struct-with-a-map-variable – sobolevn
@sobolevnこれはまさにOPが試みたものです。 JustMichaelが示唆したように、マップに文字列キーがあるため、マップは機能しません。 –