Use value of a field of a structure to define other fields of the structure

Hello everyone,

I would like to create a structure with an integer p and a Static vector A whose size depends on p. If p==0 then A will contain 2 Float64 elements otherwise A will contain p+1 Float64 elements. For a static array, we need to provide the size in advance but I don’t know how to do it.

Here is my code:

using StaticArrays

struct Utest
    p::Int64
    A::Union{SVector{2,Float64}, SVector{p+1,Float64}}
    function Utest(p::Int64)
        if p==0
        return new(p,SVector{2,Float64})
        else
        return new(p,SVector{p+1,Float64})   
        end
    end
end

UndefVarError: p not defined

Stacktrace:
[1] top-level scope at /home/mat/.julia/packages/IJulia/yLI42/src/kernel.jl:52

The problem is

— you can’t have a field as a type parameter. Also, in new(p,SVector{p+1,Float64}) you need a value, not a type.

It is hard to understand what exactly you are trying to do, but I would consider something like

struct UTest{P}
    A::SVector{P,Float64}
    function UTest(p::Int64)
        if p == 0
            new{2}(ones(SVector{2,Float64}))
        else
            new{p+1}(ones(SVector{p+1,Float64}))
        end
    end
end

eg

julia> UTest(0)
UTest{2}([1.0, 1.0])

julia> UTest(2)
UTest{3}([1.0, 1.0, 1.0])

where I just used 1s as initial values. That said, I would consider a type stable constructor instead.

Finally, please follow style conventions, it makes it much easier to help you.