Learn more about

Elixir Protocols — Implementing Inspect over custom data type

Designing custom datatype inspection

Blackode
Blackode
Sep 8 · 2 min read

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

So, our protocol is Inspect and our data-type is Student.

Overriding the inspect

Inside defimpl, we need to override inspect function.

We are simply returning our beautiful framed struct with a limited number of keys. So, whenever we do inspect call over Student type, we can see this beautifully framed struct with keys Name and Place only.

Image for post
Image for post

Note:

I just defined the keys to be printed. But the protocols are not limited to this feature.

Hope you got the idea of usage on how to implement Inspect protocol over custom data type.

Join our Telegram Channel Blackoders.

Check out the GitHub repository on Killer Elixir Tips

Image for post
Image for post

Glad if you can contribute with a ★ so it can reach the people faster.

Happy Coding !!

blackode

Coding, thoughts, and ideas.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store