Type-stability with an elastic array in a struct

james3
Mon, 06 Jun 2022 09:59:57 +0000
General Usage

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.

2 posts - 2 participants