Bringing structs and protocols together

Now that we have the %Folder{} struct defined, we can define its implementation for the Size protocol.

We'll first define the implementation for the %File.Stat{} struct, as we can then use this to implement the protocol for %Folder{}. Here's the implementation for %File.Stat{}:

$ cat examples/size_implementations_file_stat_and_folder.exdefimpl Size, for: File.Stat do  def size(file_stat), do: file_stat.sizeend# ...

With this in place, our implementation for our %Folder{} struct is as follows:

$ cat examples/size_implementations_file_stat_and_folder.ex# ...defimpl Size, for: Folder do  def size(folder) do    folder.files_info    |> Enum.map(&Size.size(&1))    |> Enum.sum()  endend

To find out the size of a folder, ...

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.