Confusing error messages when declaring mutable type containing vectors

I am trying to declare a type which contains some vectors of numbers, some containing Complex data, some containing Floats. I also want to initialise the vectors to be empty. When I try to do this, I get confusing error messages.

This is a toy example which reproduces the error message that I’m getting:

mutable struct TestType
    data::Vector{Float64}
    complexdata::Vector{Complex}
    function TestType()
        data::Vector{Float64} = Float64[]
        complexdata::Vector{Complex} = Complex[]
        return new(data, complexdata)
    end
end

And the error message:

LoadError: TypeError: in Type{...} expression, expected UnionAll, got typeof(Vector)
in expression starting at ~/Code/Julia/Examples/typestest.jl:1
top-level scope at none:0

Is this the right way to do this? How could I get this to work?
The most confusing thing is that in the program that I am trying to use this in, this error will sometimes disappear and everything will work as expected even though I have not edited the suspect code.

1 Like

That runs without error for me.

BTW I think just saying data = Float64[] would be equivalent. Also, you may want Complex{Float64} not just Complex.

You can also try:

mutable struct TestType
    data::Vector{Float64}
    complexdata::Vector{Complex}

    TestType() = new()

end

Note that this will overwrite default constructor method:

julia> a = TestType()
TestType(#undef, #undef)

julia> b = TestType([1.0], [1.0 +im])
ERROR: MethodError: no method matching TestType(::Array{Float64,1}, ::Array{Complex{Float64},2})
Stacktrace:
 [1] top-level scope at none:0