How to simply get the array struct's element array

For example:

mutable struct Coords
           x::Float64
           y::Float64
           z::Float64
 end
n = 10
v = Vector{Coords}(undef, n)
for i = 1:n
      v[i] = Coords(rand(), rand(), rand())
end

I want to get array struct v’s all element x values as vector,

julia> v[:].x
ERROR: type Array has no field x
Stacktrace:
 [1] getproperty(x::Vector{Coords}, f::Symbol)
   @ Base ./Base.jl:42
 [2] top-level scope
   @ REPL[11]:1
julia> [v[i].x for i=1:10]

This can get the result I want, but the expression is not elegant.

getproperty.(v, :x)

1 Like

Or you use a StructArray:

using StructArrays

mutable struct Coords
    x::Float64
    y::Float64
    z::Float64
end

n = 10
v = Vector{Coords}(undef, n)
for i = 1:n
    v[i] = Coords(rand(), rand(), rand())
end

sa = StructArray(v)
sa.x

@cepheid Please put your example code in triple backticks (```) so that it gets nicely formatted.