Add custom method to Base.show

I have a struct named A:

struct A
    dict::Dict
end

dict=Dict(:a=>1,:b=>2)

#show a dict in REPL(notebook in vscode)
Dict{Symbol, Int64} with 2 entries:
  :a => 1
  :b => 2

a=A(dict)

Then, I add a method to Base.show to show struct A:

Base.show(io::IO,a::A)=println(a.dict)

a
#show struct A in REPL
 Dict(:a => 1, :b => 2)

Here show A as : Dict(:a => 1, :b => 2), but I would like to show A like the original show of a Dict:


Dict{Symbol, Int64} with 2 entries:
  :a => 1
  :b => 2

How can I change the Base.show method to do this?

Using display instead of println is one way, though I would probably do something like

julia> Base.show(io::IO, a::A) = show(io, a.dict) # For one-line printing

julia> Base.show(io::IO, ::MIME"text/plain", a::A) = show(io, "text/plain", a.dict) # For multiline printing

(And I would also make sure the printed information explains that a is not a Dict, but wraps one.)

See Custom pretty-printing for more details.

1 Like

Yes, thanks, it works fine. The argument text/plain for Base.show is automattically turned to a MIME type, weird and amazing to me.