Learn more about
Elixir Protocols — Implementing Inspect over custom data type
Designing custom datatype inspection
Protocols are one of the concepts we don’t use often in our projects. I have been waiting for a moment to use protocols in one of my Elixir projects. I never got a chance to do so.
I gotta figure out myself. In one of my projects, I used to work with a large struct. Whenever I inspect the struct using IO.inspect
it is printing the enormous struct with all the keys and values which I don’t care for.
So, I re-designed the inspect output for any specific type by implementing the Inspect
protocol and overriding inspect
function.
Let’s see the Code.
Defining a Struct
We can define a struct in elixir using defstruct
defmodule Student do
defstruct name: "John", place: "Earth", address: "black street", class: "Grade 3"
end
To keep this simple, I’m using a simple struct here.
We all know that each struct in Elixir defines a custom type as the module name. So, our custom type is Student
here.
Implementing Inspect Protocol for Student type
We can implement any protocol using defimpl
as
defimpl <protocol>, for: <data-type> do
…
end