...

/

Nested Dictionary Structures

Nested Dictionary Structures

Learn about nested structs and how different accessors can reduce our code and make it dynamic.

Introduction

The various dictionary types let us associate keys with values. But those values can themselves be dictionaries. For example, we may have a bug-reporting system. We could represent this using the following:

defmodule First.MixProject do
  use Mix.Project

  def project do
    [
      app: :first,
      version: "0.1.0",
      elixir: "~> 1.12",
      start_permanent: Mix.env() == :prod,
      deps: deps()
    ]
  end

  # Run "mix help compile.app" to learn about applications.
  def application do
    [
      extra_applications: [:logger]
    ]
  end

  # Run "mix help deps" to learn about dependencies.
  defp deps do
    [
      # {:dep_from_hexpm, "~> 0.3.0"},
      # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
    ]
  end

  def hello do
    [
    IO.puts("Hello")
    ]
  end
end
Nested dictionary structures example

We may create a report for the above code as report = %BugReport{owner: %Customer{name: "Dave", company: "Pragmatic"}, details: "broken"}.

The owner attribute of the report is itself a Customer struct. We can access nested fields using regular dot notation:

iex> report.owner.company 
"Pragmatic"

But now our customer complains the company name is incorrect. It should be PragProg. Let’s fix it using the code below:

iex> report
...