# If new struct should implement show function to well print? otherwise it may cause error?

I’ve recently been learning source codes of pkg `FixedEffectModels`.

``````if false
Xall = Combination(y, Xexo, Xendo, Z)
else
Xall = Combination(y, Xexo)
println(typeof(Xall))   # it can been print
println("Xall")            #  it can been print
println(Xall)               #  it cause error
end
``````

it reports a error as follows:

``````CanonicalIndexError: getindex not defined for Combination{Float64}
``````

these code in a cell with notebook of VS code can replicate this error：

``````struct Combination{T} <: AbstractMatrix{T}
A::Tuple
cumlength::Vector{Int}
end

function Combination(A::Union{AbstractVector{T}, AbstractMatrix{T}}...) where {T}
Combination{T}(A, cumsum([size(x, 2) for x in A]))
end

Base.size(c::Combination) = (size(c.A[1], 1), c.cumlength[end])
Base.size(c::Combination, i::Integer) = size(c)[i]

function Base.view(c::Combination, ::Colon, j)
index = searchsortedfirst(c.cumlength, j)
newj = index == 1 ? j : j   - c.cumlength[index-1]
view(c.A[index], :, newj)
end
Combination([1,2,3], [4,5,6])
``````

and in a new cell with followed code works well.

``````# new cell
Combination([1,2,3], [4,5,6]);
``````

So

• why this error occurs?
• Is it cause by the lack of proper show function for struct `Combination`
• if it’s true, is it a flaw of julia?
• a more complicated question is that how can I know how many methods current object/instance can use?

You are defining a subtype of `AbstractMatrix`, which means that Julia calls the default `show` method for arrays, which in turn expects `getindex` to be defined. Hence the error.

If you don’t define `getindex`, this shouldn’t be a subtype of `AbstractMatrix`. Remove the `<: AbstractMatrix{T}` and `println` will work fine.

2 Likes

so where can I learn this information?

so is there a general way to view a variable with strange struct? It seems not so convenient to define `getindex` just for view a variable.

You should define `getindex` if it is a subtype of `AbstractMatrix`, otherwise your type is broken. Why do you want to call `Combination` a matrix subtype if it doesn’t support indexing?

I am sorry I get it. I just what to see what the content of a instance(sometimes we can see the definition directly. here I complement it by draw it from other place) and in other language a easy is to print it.

`dump(x)` works even if you have broken `show`.

thanks a lot! It works well. If it wasn’t for you, I wouldn’t have thought that `dump` could be used in this way