specs: document for-loop by-reference capture (for xs: (*elem))

Covers the *elem pointer binding: zero-copy pass to *T params, write-back via elem.*, value-position auto-deref, and pointer-subject match.
This commit is contained in:
agra
2026-05-31 10:32:05 +03:00
parent 185df9afb7
commit d70a7084ff

View File

@@ -1556,6 +1556,8 @@ runtime form.
for iterable: (elem) { } // element alias (no copy)
for iterable: (elem, ix) { } // element + index
for iterable: (_, ix) { } // index only
for iterable: (*elem) { } // element pointer (*T) — by-reference
for iterable: (*elem, ix) { } // element pointer + index
```
Iterates over arrays and slices. The capture clause after `:` binds loop variables:
- The first name is the element capture (non-reassignable alias into the array/slice)
@@ -1564,6 +1566,18 @@ Iterates over arrays and slices. The capture clause after `:` binds loop variabl
The element capture is a direct alias — reads and field writes go to the original array element. Direct reassignment of the capture (`elem = x`) is a compile error.
**By-reference capture (`*elem`)** binds the element to a *pointer* into the collection (`*T`) instead of a value — no per-element copy. It GEPs straight into the array/slice backing, so:
- Passing it onward is zero-copy — `f(elem)` where `f` takes `*T` hands over the pointer, not a copy.
- Writes through it land in the original: `elem.* = v` (or `elem.field = v`).
- In a value position the pointer auto-derefs to the element: `elem + 1` reads the value, and `if elem == { … }` matches the pointee (a pointer subject matches through the deref). Where a `*T` is expected, the pointer is passed as-is.
```sx
events := plat.poll_events(); // []Event
for events: (*ev) { // ev : *Event — no copy
pipeline.dispatch_event(ev); // passes the pointer
}
```
`break;` exits the loop. `continue;` skips to the next iteration.
```sx
arr : [5]s32 = .[1, 2, 3, 4, 5];