Property destructuring

Unter Property destructoring I found a simple example for property destructuring.

(; b, a) = (a=1, b=2, c=3)

I understand how it works, but it is not clear to me where you can use this practically.

Can someone show me a small executable example code that opens up the practical application for me?

Many thanks in advance

It’s useful as soon as the named tuple is a variable instead of a literal.

Some examples in this related thread.

1 Like

Here is an example - imagine that tpl is returned by some function and is not a literal.

tpl = (a=1, b=2, c=3)

a = tpl.a
b = tpl.b

# or

a, b = tpl.a, tpl.b

# or using destructuring

(; a, b) = tpl

Now, we can agree that (; a, b) = tpl saves a few keystrokes. And if you actually want to extract more fields (imagine (; a, b, c, d, e) = x), then it becomes even more obvious that it saves some time.

Also, it works even if your right side is a struct (even more, it works for any type that has the getproperty method defined).

This is just syntactic sugar to make things more convenient for the developer. The other forms from my example are also OK.


Here is a sketch of some code I’m currently working on that uses destructuring for its convenience:

lens = (; f1, α, β, γ, y3, sinθ, ϵᵣ)
opts = (;
    ap_split = 2, 
    ap_point = 0.0,
    ap_compensate = false,
    bp_split = 2,
    bp_point = 0.0,
    bp_compensate = true,
    ap_apex = 0.046,
    bp_apex = 0.046,

lens = RotmanLens.rl_solve(lens)
lens = RotmanLens.port_apertures(lens, opts) 
lens = RotmanLens.rl_excite(lens, opts)

The functions are set up like this:

function rl_solve(lens::NamedTuple)
    (; f1, α, β, γ, y3, sinθ, ϵᵣ) = lens # Deconstruct fields
    xya = similar(y3, SV2)
    xyb = similar(sinθ, SV2)
    w = similar(y3)
    ... # Compute entries of xya, xyb, w
    return merge(lens, (; xya, xyb, w))

Each function destructures whatever fields are needed from lens::NamedTuple and merges in the part that is computed locally. It is much more convenient than tracking many inputs and outputs.


Thank you for the very good help to all of you. I am amazed