Structs

Structs are an abstraction built on top of maps. We define a struct inside a module, with the defstruct construct. The struct's name is the name of the module it's being defined in (which means you can only define one struct per module). To defstruct, we pass a keyword list, which contains the key-value pairs that define the fields that struct has, along with their default values. Let's define a Folder struct:

$ cat examples/folder.exdefmodule Folder do  defstruct name: "new folder", files_info: [], path: nilend 

We can now use it in our IEx session:

iex> %Folder{}%Folder{files_info: [], name: "new folder", path: nil}iex> %Folder{}.name"new folder"iex> %Folder{}.files_info[]

Elixir already has a File module, which provides several ...

Get Mastering Elixir 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.