Learn Elixir through Q&A: Structs

This and the other “Deck” posts are a repurposing of flashcard study decks to Q&A blog posts.

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: "lisa@gmail.com", age: 29, name: "Lisa" end ```

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: "lisa@gmail.com", name: "Lisa"} jim = %User{name: "Jim", email: "jim@gmail.com"} => %User{age: 29, email: "jim@gmail.com", name: "Jim"} ```

How do you update a Struct?

The same way you would update a `Map`. Using the `|` operator: ``` jim = %User{name: "Jim", email: "jim@gmail.com", age: 24} jim = %{jim | age: 30} => %User{age: 30, email: "jim@gmail.com", 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: "jim@gmail.com", age: 24} jim.email => "jim@gmail.com" ```

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"] end ```