Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

elixir

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?

like image 934
bullfrog Avatar asked Jun 18 '15 23:06

bullfrog


People also ask

How do you declare a struct in Elixir?

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.

What is map in Elixir?

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}

What is __ module __ In Elixir?

__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.


1 Answers

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"} 
like image 145
José Valim Avatar answered Sep 18 '22 21:09

José Valim