# Vector operation to vector of structures

**URL:** <https://discourse.julialang.org/t/vector-operation-to-vector-of-structures/112927>\
**Category:** General Usage\
**Created:** [April 14, 2024, 4:05pm UTC](https://discourse.julialang.org/t/vector-operation-to-vector-of-structures/112927 "2024-04-14T16:05:01Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Joris\_Pinkse](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/joris_pinkse/32/216398_2.png) [@Joris\_Pinkse](https://discourse.julialang.org/u/Joris_Pinkse)\
**Post date:** [April 14, 2024, 4:05pm UTC](https://discourse.julialang.org/t/vector-operation-to-vector-of-structures/112927/1 "2024-04-14T16:05:01Z")

</div>

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!

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

```

---

<div class="post-metadata">

**Author:** ![jules](https://avatars.discourse-cdn.com/v4/letter/j/41988e/32.png) [@jules](https://discourse.julialang.org/u/jules)\
**Post date:** [April 14, 2024, 5:47pm UTC](https://discourse.julialang.org/t/vector-operation-to-vector-of-structures/112927/2 "2024-04-14T17:47:13Z")

</div>

Does this cover your use case?

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

```
