官术网_书友最值得收藏!

  • Mastering Elixir
  • André Albuquerque Daniel Caixinha
  • 225字
  • 2021-08-05 10:42:51

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.ex
defimpl Size, for: File.Stat do
def size(file_stat), do: file_stat.size
end

# ...

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()
end
end

To find out the size of a folder, we sum the size of each file it contains. As such, this implementation iterates through our files_info list, using the Size implementation for %File.Stat{} to get the size of each file, summing all the sizes in the end. In the following snippet, we can see this implementation being used on the folder variable we just defined:

iex> Size.size(folder)
779

With this, we can see the full power of mixing structs and protocols, which lets us have polymorphic functions based on the data type of their arguments. We now have a common interface, Size.size(data), that allows us to find out the size of pretty much anything we want, provided that we implement the Size protocol for the data type we're interested in.

主站蜘蛛池模板: 德江县| 福州市| 衡山县| 无极县| 洛扎县| 通许县| 连城县| 托克托县| 宽城| 灯塔市| 西华县| 鄂尔多斯市| 杨浦区| 南川市| 霍邱县| 凌海市| 阳江市| 南宫市| 美姑县| 海南省| 临汾市| 曲阜市| 东明县| 清原| 儋州市| 清苑县| 临邑县| 托里县| 敦煌市| 永春县| 巧家县| 东方市| 仁怀市| 金华市| 集安市| 广平县| 蓝山县| 天津市| 荣成市| 依兰县| 新安县|