Custom printing of struct getting printed before string

I have a struct that I would like to define a custom way of printing it. This is done by overloading the Base.show function:

struct customType
    a::Int
    b::Int
end

function Base.show(io::IO, state::customType)
    print("$(state.a), $(state.b)")
end

This works fine if I just call println(A) . However, if I call it in the context of a string, i.e. println("Custom struct is: $(A)"), the printing of A happens before the rest of the string. i.e the output of the code

A = customType(1, 2)
println(A)
println("custom type is $(A)")

is

1, 2
1, 2custom type is

How do I fix this?

You must pass io to print in your definition of show.

2 Likes

Got it, thanks!

1 Like