Vector operation to vector of structures

Good morning,

If I have a vector of structs say s, I know I can set and get a field for all elements at once by using setfield!. and getfield. . Is there a convenient way of ensuring that I can use s.x . I guess there is scope for ambiguity, but I’m ok with having s.x being a view.

Thanks!

mutable struct S
    x
    y
end



function runme()
    s = [ S( randn( 2 )...) for j ∈ 1:3 ]
    s2 = [ S( randn( 2 )...) for j ∈ 1:3 ]
    println( s )
    println( s2 )
    setfield!.( s, :x, getfield.( s2, :y ) .+ 1 )
    # would like to write s.x = s2.y .+ 1
    println( s )
end

Does this cover your use case?

julia> using StructArrays

julia> mutable struct S
           x
           y
       end

julia> s = StructArray([ S( randn( 2 )...) for j ∈ 1:3 ])
3-element StructArray(::Vector{Any}, ::Vector{Any}) with eltype S:
 S(-2.2813758448781507, 1.0576333529094646)
 S(0.8757842483382511, -0.9115113215165129)
 S(0.529173572687709, 0.6783507892731278)

julia> s2 = StructArray([ S( randn( 2 )...) for j ∈ 1:3 ])
3-element StructArray(::Vector{Any}, ::Vector{Any}) with eltype S:
 S(-0.44020090132169276, 0.6585031850841647)
 S(-0.35800735773957343, 0.41594747368930296)
 S(-0.7756397613064178, -0.9177624933053972)

julia> s.x
3-element Vector{Any}:
 -2.2813758448781507
  0.8757842483382511
  0.529173572687709

julia> s.x .= s2.y .+ 1
3-element Vector{Any}:
 1.6585031850841647
 1.415947473689303
 0.08223750669460284

julia> s
3-element StructArray(::Vector{Any}, ::Vector{Any}) with eltype S:
 S(1.6585031850841647, 1.0576333529094646)
 S(1.415947473689303, -0.9115113215165129)
 S(0.08223750669460284, 0.6783507892731278)
1 Like