I know its possible to create a struct via %User{ email: '[email protected]' }
. But if I had a variable params = %{email: '[email protected]'}
is there a way to create that struct using that variable for eg, %User{ params }
.
This gives an error, just wondering if you can explode it or some other way?
To define a struct, the defstruct construct is used: iex> defmodule User do ...> defstruct name: "John", age: 27 ...> end. The keyword list used with defstruct defines what fields the struct will have along with their default values. Structs take the name of the module they're defined in.
12.3) Maps are the "go to" key-value data structure in Elixir. Maps can be created with the %{} syntax, and key-value pairs can be expressed as key => value : iex> %{} %{} iex> %{"one" => :two, 3 => "four"} %{3 => "four", "one" => :two}
__MODULE__ is a compilation environment macros which is the current module name as an atom. Now you know alias __MODULE__ just defines an alias for our Elixir module. This is very useful when used with defstruct which we will talk about next. In the following example, we pass API.
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With