Assigning struct to multiple variables

I would like to export a struct to variables. Say I have the following struct

struct point
       x::Float64
       y::Float64
end

and I use it to define a point

A=point(3.0,4.0)

Is there a concise way to extract the components, like

x,y=A

However, this throws the following error

ERROR: MethodError: no method matching iterate(::point)

I am aware that x,y=A.x, A.y works. However, I am looking for little more concise since the structs that I work with contain many fields with long names.

(; x, y) = A

2 Likes

I think you mean:

(; x,y) = A

See property destructuring in the Julia manual.

4 Likes

I edited my comment to fix it. The parenthesis are of course necessary, as otherwise it’s equivalent to ending the previous statement (the semicolon) and then normal iterative destructuring.

1 Like

Unfortunately it doesn’t work in v1.6.x, but the manual doesn’t mention that.

Works like a charm on v1.8, thanks!

In 1.6 you can use

using Parameters
@unpack x, y = p

Ps. If you are actually representing points, take a look at FieldVector type of Static arrays.jl

1 Like