Learn more about

Elixir Protocols — Implementing Inspect over custom data type

Designing custom datatype inspection

Malreddy Ankanna
blackode
Published in
2 min readSep 8, 2020

--

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

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

--

--

Malreddy Ankanna
blackode

Programmer & Writer, I write about coding, thoughts, ideas, personal musings, technical articles, and tutorials.https://bio.link/blackode