defmodule Airport do defstruct [:id, :name] end defmodule Direction do defstruct [:origin, :destination] def example do madrid = %Airport{id: "MAD", name: "Madrid"} riga = %Airport{id: "RIX", name: "Riga"} %Direction{origin: riga, destination: madrid} end end
popular = Enum.map(1..5, fn _ -> Direction.example end) # => # [%Direction{destination: %Airport{id: "MAD", name: "Madrid"}, # origin: %Airport{id: "RIX", name: "Riga"}}, # %Direction{destination: %Airport{id: "MAD", name: "Madrid"}, # origin: %Airport{id: "RIX", name: "Riga"}}, # %Direction{destination: %Airport{id: "MAD", name: "Madrid"}, # origin: %Airport{id: "RIX", name: "Riga"}}, # %Direction{destination: %Airport{id: "MAD", name: "Madrid"}, # origin: %Airport{id: "RIX", name: "Riga"}}, # %Direction{destination: %Airport{id: "MAD", name: "Madrid"}, # origin: %Airport{id: "RIX", name: "Riga"}}]
defimpl String.Chars, for: Airport do def to_string(airport) do "#{airport.name} (#{airport.id})" end end defimpl String.Chars, for: Direction do def to_string(direction) do "#{direction.origin} → #{direction.destination}" end end
Enum.each(popular, fn(x) -> IO.puts(x) end) # => # Riga (RIX) → Madrid (MAD) # Riga (RIX) → Madrid (MAD) # Riga (RIX) → Madrid (MAD) # Riga (RIX) → Madrid (MAD) # Riga (RIX) → Madrid (MAD)
to_string
as part of the implementation of the String.Chars
protocol.to_string
for airports this would not work: "#{direction.origin} → #{direction.destination}"
Source: https://habr.com/ru/post/328208/
All Articles