In order to make a new type printable in Julia, which methods should one define? I believe that one should only define show
, which will then induce the behavior of other functions like:
Which of these methods need to be defined for a new type?
If the Base source is any reliable reference, base/version.jl
has only print()
and show
defined (and show
depends on print
)
function print(io::IO, v::VersionNumber)
print(io, v.major)
print(io, '.')
print(io, v.minor)
print(io, '.')
print(io, v.patch)
if !isempty(v.prerelease)
print(io, '-')
print_joined(io, v.prerelease,'.')
end
if !isempty(v.build)
print(io, '+')
print_joined(io, v.build,'.')
end
end
show(io, v::VersionNumber) = print(io, "v\"", v, "\"")
It seems at this point it is up to you if you want to rely on one common function; you just implement all such functions that way. Example:
type Foo
end
import Base.string
function string(x::Foo)
return "a Foo()"
end
import Base.print
print(io::IO, x::Foo) = print(io, string(x))
import Base.show
show(io::IO, x::Foo) = print(io, "This is ", x)
-
julia> f = Foo()
This is a Foo()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With