read methods for composite types


I wasn’t sure whether it’s a bug or intended behaviour, so I’m posting it here.

I run into a possible inconsistency in read methods when applied to a composite type. See the following example.

Let’s create a simple composite type that stores an integer

julia> struct myint

and a stream from which we would like to read the value

julia> stream = IOBuffer()
IOBuffer(data=UInt8[...], readable=true, writable=true, seekable=true, append=false, size=0, maxsize=Inf, ptr=1, mark=-1)

julia> write(stream, 1)

Now, reading directly into Int works fine as expected

julia> seekstart(stream)
julia> read(stream, Int)

but reading into myint fails

julia> seekstart(stream)
julia> read(stream, myint)
ERROR: MethodError: Cannot `convert` an object of type Type{myint} to an object of type Array{UInt8,1}
This may have arisen from a call to the constructor Array{UInt8,1}(...),
since type constructors fall back to convert methods.
 [1] read(::Base.AbstractIOBuffer{Array{UInt8,1}}, ::Type{T} where T) at ./io.jl:528

Curiously, reading into an array of myint works!

julia> seekstart(stream)
julia> read(stream, myint, 1)
1-element Array{myint,1}:

Now, is it a bug or a desired behaviour? I would expect read either to succeed or fail in both cases.