, 5 tweets, 2 min read Read on Twitter
Struct wizards Activate!

#elixirnewbie

1. The shorthand sigil syntax is great for structs.

defmodule User do
destruct ~w[name email]a
end

The ~w is a sigil with an array of words; the trailing a makes these atoms; the [] instead of () is a valid use of delimiters.
2. Structs are maps, with one extra key:

u = %User{}
-> %User{email: nil, name: nil}
Map.keys u
-> [:__struct__, :email, :name]
u.__struct__
-> User
3. Structs don't implement any Map protocols:

u[:name]
-> ...User does not implement the Access behaviour
u |> Enum.map(f(x) -> x end)
-> ...protocol Enumerable not implemented for %User...
4. Create a new struct by piping with the __struct__ function:

def new(fields)
fields
|> User.__struct__
|> validate
|> ...
end
...
User.new(name: "BT", email: "struct@bucket.com")
5. Require struct fields with @enforce_keys. To require name:

...
@enforce_keys [:name]
destruct [:name, :email]
...
Missing some Tweet in this thread?
You can try to force a refresh.

Like this thread? Get email updates or save it to PDF!

Subscribe to Bruce Tate
Profile picture

Get real-time email alerts when new unrolls are available from this author!

This content may be removed anytime!

Twitter may remove this content at anytime, convert it as a PDF, save and print for later use!

Try unrolling a thread yourself!

how to unroll video

1) Follow Thread Reader App on Twitter so you can easily mention us!

2) Go to a Twitter thread (series of Tweets by the same owner) and mention us with a keyword "unroll" @threadreaderapp unroll

You can practice here first or read more on our help page!

Follow Us on Twitter!

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just three indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3.00/month or $30.00/year) and get exclusive features!

Become Premium

Too expensive? Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal Become our Patreon

Thank you for your support!