To get custom printing of a user-defined type, you only have to overload 
the show method:

julia> type Pt
       x::Int
       y::Int
       end

julia> Pt(1,2)
Pt(1,2)

julia> Base.show(io::IO, p::Pt) = print(io, "Pt: x=$(p.x), y=$(p.y)")
show (generic function with 86 methods)

julia> Pt(1,2)
Pt: x=1, y=2

julia> [Pt(1,2), Pt(3,4), Pt(5,6)]
3-element Array{Pt,1}:
 Pt: x=1, y=2
 Pt: x=3, y=4
 Pt: x=5, y=6

julia> println(Pt(1,2))
Pt: x=1, y=2

julia> display(Pt(1,2))
Pt: x=1, y=2


On Monday, April 20, 2015 at 3:41:27 PM UTC-4, Matt Bauman wrote:
>
> You can take a look at xdump (
> https://github.com/JuliaLang/julia/blob/f7322fe8eb14dc06b65c05e8b8f3d1dbd89b684e/base/show.jl#L739-L759)
>  
> as a starting point.  Most of builtin types (like Dict) have custom display 
> code to only show the user-relevant parts in a sensible manner.  They do 
> this by specializing the display, show, and/or print methods.
>
> On Monday, April 20, 2015 at 3:16:28 PM UTC-4, Kuba Roth wrote:
>>
>> I'm not sure if this was brought before. Basically I've got lot's of 
>> fields in my custom type and would like to tweak the println function to 
>> include also the field name before printing each value. This tweak will 
>> tremendously help me with debugging my output. 
>>
>> For instance this simplified example gives the following output: 
>>
>> type myType 
>>    myName::Int 
>>    myValue::String 
>> end 
>>
>> Dict(7=>myType(5,"CCC"),3=>myType(3,"BBB"),1=>myType(1,"AAA")) 
>>
>> And this line is the (non-existing custom prinln) output I'd like to get: 
>>
>> Dict(7=>myType(myName:5,myValue:"CCC"),3=>myType(myName:3,myValue:"BBB"),1=>myType(myName:1,myValue:"AAA"))
>>  
>>
>>
>>
>> Before start looking in the details I'd like to find out if anybody had 
>> similar idea before? Perhaps this is not a new thing and something similar 
>> already exists in the form of a library? 
>>
>> The other question I have is how to make the custom print function 
>> generic enough? 
>> I'd like to mimic the behavior of println this way so it has to work with 
>> any data type. At the moment it is not clear how println determines which 
>> fields of a type to output. 
>>
>> For instance for the Dict type which has these fields 
>> :slots 
>> :keys 
>> :vals 
>> :ndel 
>> :count 
>>
>> How can we tell only keys and values are 'printable'? 
>>
>> Thank you 
>>
>

Reply via email to