Overriding Base.show with multi-line string returns literal "\n"

Hi,
I have a composite struct ABC with various fields A,B,C, which I want to display in a clear way on the screen (and later in Jupyter, but starting with REPL/console).

Here’s my code:

struct ABC
    A::Vector{Int64}
    B::Vector{Float32}
    C::Vector{String}
end

abc = ABC(
    [1,2,3],
    [4.5, 6.7, 8.9],
    ["hello", "world"]
)

function Base.show(io::IO, x::ABC)
    show(io,
    """
    A:
        $(x.A)
    
    B:
        $(x.B)

    C:
        $(x.C)
    """)
end

println(abc)

However, it shows a string with “\n” rather than actual newlines:

"A:\n    [1, 2, 3]\n\nB:\n    Float32[4.5, 6.7, 8.9]\n\nC:\n    [\"hello\", \"world\"]\n"

What am I missing?

Note: also tried PrettyPrint.jl and PrettyPrinting.jl but they seem to return similar output to print for this case.

Inside your Base.show implementation, you want to call print, not show on the string. show will always give you some output that you can ideally copy-and-paste into the REPL and get back the same object. print is for when you want to just print the string as-is, but it falls back to show for most other objects.

4 Likes