All posts

Elixir Structs for new developers

This and the other “Deck” posts are a repurposing of flashcard study decks to Q&A blog posts. Google was not showing love to this content as a set of flashcards and I didn’t want to delete them entirely, I hope you find it useful.

What are Structs?

An Elixir key/value data structure. They are also extensions of the Map module and thus share similar functionality.

What are some differences between Structs and Maps?

  • Structs do not have access to Enum functions like Maps do
  • The keys for a Struct must be included in its definition.
  • If a key is provided to a Struct that the Struct is unaware of an error will be raised.
  • Only atoms can be used as keys in a Struct.

How is a Struct defined?

From inside a module using the defstruct macro. Ex:

defmodule User do 
  defstruct email: "", age: 29, name: "Lisa" 

How would you instantiate a new Struct using the previous cards User struct definition?

The examples below are two separate structs created from the User struct.

lisa = %User{} => %User{age: 29, email: "", name: "Lisa"} 
jim = %User{name: "Jim", email: ""} 
=> %User{age: 29, email: "", name: "Jim"}

How do you update a Struct?

The same way you would update a Map. Using the | operator:

jim = %User{name: "Jim", email: "", age: 24} 
jim = %{jim | age: 30} 
=> %User{age: 30, email: "", name: "Jim"}

How do you access a value in a Struct?

The same way you would access a value in a Map:

jim = %User{name: "Jim", email: "", age: 24} 
=> ""

How do you delete a key/value from a Struct?

You don’t. Struct definitions are constant. If you need a more dynamic key/value store, a Map should be used.

Can you set a Struct key without a default value?

Yes, but it must come at the end of the beginning of the definition. Ex:

defmodule User do 
  defstruct [:email, age: 29, name: "Lisa"]

More Elixir lang decks