Skip to content

Commit a9047b6

Browse files
ArunS-tacksimeonschaub
authored andcommitted
doc for property destructuring (JuliaLang#41189)
Co-authored-by: Simeon Schaub <[email protected]>
1 parent 36d4d3e commit a9047b6

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

doc/src/manual/functions.md

+36-1
Original file line numberDiff line numberDiff line change
@@ -475,6 +475,23 @@ Base.Iterators.Rest{Base.Generator{UnitRange{Int64}, typeof(abs2)}, Int64}(Base.
475475

476476
See [`Base.rest`](@ref) for details on the precise handling and customization for specific iterators.
477477

478+
## Property destructuring
479+
480+
Instead of destructuring based on iteration, the right side of assignments can also be destructured using property names.
481+
This follows the syntax for NamedTuples, and works by assigning to each variable on the left a
482+
property of the right side of the assignment with the same name using `getproperty`:
483+
484+
```julia
485+
julia> (; b, a) = (a=1, b=2, c=3)
486+
(a = 1, b = 2, c = 3)
487+
488+
julia> a
489+
1
490+
491+
julia> b
492+
2
493+
```
494+
478495
## Argument destructuring
479496

480497
The destructuring feature can also be used within a function argument.
@@ -493,7 +510,25 @@ julia> gap(minmax(10, 2))
493510
Notice the extra set of parentheses in the definition of `gap`. Without those, `gap`
494511
would be a two-argument function, and this example would not work.
495512

496-
For anonymous functions, destructuring a single tuple requires an extra comma:
513+
Similarly, property destructuring can also be used for function arguments:
514+
515+
```julia
516+
julia> foo((; x, y)) = x + y
517+
foo (generic function with 1 method)
518+
519+
julia> foo((x=1, y=2))
520+
3
521+
522+
julia> struct A
523+
x
524+
y
525+
end
526+
527+
julia> foo(A(3, 4))
528+
7
529+
```
530+
531+
For anonymous functions, destructuring a single argument requires an extra comma:
497532

498533
```
499534
julia> map(((x,y),) -> x + y, [(1,2), (3,4)])

0 commit comments

Comments
 (0)