Turn maps (and keyword lists) into structs

One nice way of turning a map or keyword list into an existing struct is to use struct/2 or struct!/2.

attrs = %{name: "Frodo", age: 35, email: "frodo@hobbiton.com"}

struct(User, attrs)
#=> %User{name: "Frodo", age: 35, email: "frodo@hobbiton.com"}

What about attributes that aren’t defined in the struct?

  • struct/2 will drop them 👋
  • struct!/2 will raise an error 💥

But there’s more!

Not only can they create structs, they can also update them:

attrs = %{name: "Frodo", age: 35, email: "frodo@hobbiton.com"}

user = struct!(User, attrs)
#=> %User{name: "Frodo", age: 35, email: "frodo@hobbiton.com"}

struct!(user, age: 36)
#=> %User{name: "Frodo", age: 36, email: "frodo@hobbiton.com"}

Want the latest Elixir Streams in your inbox?

    No spam. Unsubscribe any time.