Maps and Structs

The map has rapidly become the go-to data structure for Elixir programmers. For the purposes of this section, we’re going to treat maps and structs as basically the same thing. In IEx, you can see that a struct is actually implemented as a map. Let’s take a peek under the hood:

 iex(1)>​ ​defmodule​ User ​do
 ...(1)>​ defstruct [​:name​, ​:email​]
 ...(1)>​ ​end
 {:module, User, ...}
 iex(2)>​ map = %User{}
 %User{email: nil, name: nil}
 iex(3)>​ is_map(map)
 true
 iex(4)>​ map.__struct__
 User

So a User is actually a map. All structs have a __struct__ field that plain Elixir maps don’t have. Let’s look at the functions User supports. In IEx, type “User.” and then type tab, twice:

 iex(5)>​ User.__struct__
 __struct__/0 ...

Get Designing Elixir Systems With OTP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.