在Elixir中,如何使用地图变量初始化结构 [英] In Elixir how do you initialize a struct with a map variable
本文介绍了在Elixir中,如何使用地图变量初始化结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道可以通过%User {电子邮件:‘blah@blah.com’}
创建结构。但是,如果我有一个变量 params =%{email:'blah@blah.com'}
,有一种方法可以使用该变量创建该结构,例如%User {params}
。
I know its possible to create a struct via %User{ email: 'blah@blah.com' }
. But if I had a variable params = %{email: 'blah@blah.com'}
is there a way to create that struct using that variable for eg, %User{ params }
.
这是一个错误,只是想知道您是否可以将其爆炸? p>
This gives an error, just wondering if you can explode it or some other way?
推荐答案
您应使用 struct / 2
函数。从文档中:
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"}
这篇关于在Elixir中,如何使用地图变量初始化结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文