Struct pretty printing through defimpl Inspect

The goal is to make sure a struct is printed in a human readable format when sent to IO.inspect.

This is new to me, but I found it’s apparently possible to use defimpl to achieve that… here is what I am attempting

defimpl Inspect, for: MyLib.Data do
  @byte 8

  def inspect(data, _opts) do
    hex_data = Base.encode16(data, case: :lower)
    data_size = byte_size(data) * @byte

    "<<0x#{hex_data}::#{data_size}>>"
  end
end

It should end up printing a bitstring in a format similar to this: <<0x0a8d286b11b98f6cb2585b627ff44d12059560acd430dcfa1260ef2bd9569373::256>>.

Problem is, apparently I can’t use the Base module in there… why?

Here is the error I get:

got FunctionClauseError with message \"no function clause matching in Base.encode16/2\" 
while inspecting %{__struct__: MyLib.Data, value: <<...>>}

Hey @RooSoft the error is saying that you have a function clause error, not that you can’t use the module. This is probably because you’re passing the whole struct into Base.encode16 when you probably only want to pass in the binary value eg:

hex_data = Base.encode16(data.value, case: :lower)
data_size = byte_size(data.value) * @byte
1 Like

Thank you so much Ben! That’s the solution…

1 Like