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

**URL:** <https://discourse.julialang.org/t/use-value-of-a-field-of-a-structure-to-define-other-fields-of-the-structure/36887>\
**Category:** General Usage\
**Tags:** question\
**Created:** [April 2, 2020, 5:07am UTC](https://discourse.julialang.org/t/use-value-of-a-field-of-a-structure-to-define-other-fields-of-the-structure/36887 "2020-04-02T05:07:17Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![mleprovost](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mleprovost/32/7166_2.png) [@mleprovost](https://discourse.julialang.org/u/mleprovost)\
**Post date:** [April 2, 2020, 5:07am UTC](https://discourse.julialang.org/t/use-value-of-a-field-of-a-structure-to-define-other-fields-of-the-structure/36887/1 "2020-04-02T05:07:17Z")

</div>

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:

```julia
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

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [April 2, 2020, 7:35am UTC](https://discourse.julialang.org/t/use-value-of-a-field-of-a-structure-to-define-other-fields-of-the-structure/36887/2 "2020-04-02T07:35:40Z")

</div>

The problem is

> [@mleprovost](#):
>
> `SVector{p+1,Float64}`

— 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

```julia
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
julia> UTest(0)
UTest{2}([1.0, 1.0])

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

```

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

Finally, please follow [style conventions](https://docs.julialang.org/en/v1/manual/style-guide/), it makes it much easier to help you.
