Confusion over string interpolation of a struct

I would like to write a summary of a struct as a string.

So I did the following:

julia> struct Cell{R<:Int}
           row::R
           col::R
       end

julia> import Base.print

julia> print(io::IO, c::Cell) = print(">>($(c.row),$(c.col))")
print (generic function with 32 methods)

julia> c=Cell(2,3)
Cell{Int64}(2, 3)

julia> "it is $c currently"
>>(2,3)"it is  currently"

I think it is clear that this is not useful output.

My inclination would have been to write a string() method but if I understand the docs correctly print() is the preferred method to overload:

“Both concatenation and string interpolation call string to convert objects into string form. However, string actually just returns the output of print, so new types should add methods to print or [show](I/O and Network · The Julia Language{IO, Any}) instead of string.”

Could somebody point me in teh right direction, please?

Many thanks.

Note that your print function does not use the io argument, i.e., always prints to stdout. In the string interpolation print gets passed an IOBuffer instead and should write to that.
Long story short, your example works for me if I define:

print(io::IO, c::Cell) = print(io, ">>($(c.row),$(c.col))")
1 Like

Doh. Thank you. Time to shut down for the day :slight_smile:

Have a look at the docstring for show. I believe you should overload show rather than print.

5 Likes