# How can I improve this piece of code?

Hello,

I am new to Julia and I’m trying to do one of my first codes. I have created two Structs that can be described as follows:

``````struct Struct1
a::Int
b::SVector{value1, Int}
c::Int
end

struct Struct2
d::SVector{value1, Int}
end
``````

I have the following function:

``````function MyFunction(x::Struct1)
return  [(Struct2(d)) for d in Iterators.product(0:value2.-x.b,0:value2.-x.b) if sum(d)<=x.a]
end
``````

It works when `value1 = 2`, but I want to know how can I put it so if `value1=4` it changes.

Thanks You cannot have a `struct` dynamically change like that. What would happen with all the objects that had just two elements? They would gain two new undefined elements immediately? What you can do is to use a struct with type parameters, and so allow many different versions of the type with different lengths.

``````julia> using StaticArrays

julia> struct Struct1{N}
a::Int
b::SVector{N, Int}
c::Int
end

julia> struct Struct2{N}
d::SVector{N, Int}
end

julia> function MyFunction(x::Struct1{N}) where {N}
return  [(Struct2{N}(SVector{N}(d...))) for d in Iterators.product(ntuple((i -> 0:N .- x.b[i]), N)...) if sum(d)<=x.a]
end

julia> MyFunction(Struct1{2}(1, SVector{2, Int}(1, 1), 1))
3-element Array{Struct2{2},1}:
Struct2{2}([0, 0])
Struct2{2}([1, 0])
Struct2{2}([0, 1])

julia> MyFunction(Struct1{3}(1, SVector{3, Int}(1, 1, 1), 1))
4-element Array{Struct2{3},1}:
Struct2{3}([0, 0, 0])
Struct2{3}([1, 0, 0])
Struct2{3}([0, 1, 0])
Struct2{3}([0, 0, 1])

``````

I assumed `value2` weas a mistake and you meant `value1`.

4 Likes

Hello,

Yes, you are totally right. I am sorry, I am new and there are some things that I still don’t know.

Thank you so much for your help.

1 Like