How can I improve this piece of code?

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