Type-stability with an elastic array in a struct

I have defined a struct that contains an elastic array, similar to the following.

struct MyStruct
    myelas::ElasticMatrix{Int64}
end 

However, @code_warntype shows the following is not type-stable.

function test_struct(n)
    mystruct = MyStruct(ElasticMatrix{Int64}(undef, n, 0))
    append!(mystruct.myelas, ones(Int64, n))
    return mystruct
end

If I implement the same code here without the struct then all is okay.

function test(n)
    myelas = ElasticMatrix{Int64}(undef, n, 0)
    append!(myelas, ones(Int64, n))
    return myelas
end

How should I be defining MyStruct to achieve type-stability? Thanks.

Yes an elastic array has more parameters than that. In your case you could do

struct MyStruct
    myelas::typeof(ElasticMatrix{Int64}(undef, 0, 0))
end

to get the concrete type without delving into the internals of ElasticArrays.

3 Likes