Labeled Control Flow and Loop Variables
Reference index · Summary of this topic
Go restricts a label to immediately precede the enclosing statement (e.g. a for). Equivalent behavior is produced with a placed label and a goto:
Break Label
OuterLoop:
for i = 0; i < n; i++ {
for j = 0; j < m; j++ {
switch a[i][j] {
case nil:
state = Error
break OuterLoop
}
}
}
becomes (with a a [][]*int; the Go label stays in place, and the break target is emitted as break_OuterLoop:; after the loop):
OuterLoop:
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
switch (a[i][j]) {
case var ᴛ when ᴛ == default: {
state = Error;
goto break_OuterLoop;
break;
}}
}
continue_OuterLoop:;
}
break_OuterLoop:;
The nil label is not a C# constant, so the clause compares in a when guard (see
Expression Switch Statements).
Continue Label
RowLoop:
for y, row := range rows {
for x, data := range row {
if data == endOfRow {
continue RowLoop
}
row[x] = data + bias(x, y)
}
}
becomes (continue_RowLoop: placed at the end of the labeled loop’s body — so goto continue_RowLoop from the inner loop lands there and the outer loop proceeds to its next iteration; break_RowLoop:; follows the outer loop):
RowLoop:
foreach (var (y, row) in range(rows)) {
foreach (var (x, data) in range(row)) {
if (data == endOfRow) {
goto continue_RowLoop;
}
row[x] = data + bias(x, y);
}
continue_RowLoop:;
}
break_RowLoop:;
Both the break_<label>/continue_<label> labels are emitted for a labeled for and a labeled range/foreach loop (the label target is placed regardless of loop kind; a missing one is CS0159 “no such label”). Guarded by the ForVariants behavioral test (labeled range with nested continue/break).
A labeled switch, type switch or select takes only the break label: break_<label>:; follows the
C# switch it lowers to, so break L from a nested switch or loop, or from the statement’s own
clause, leaves it as in Go. A labeled select lacked the label until 2026-11-29 and failed CS0159; a
break L clause also keeps a blocking select from taking the trailing return default; a
value-returning function otherwise gets after it. Guarded by LabeledSelectBreak (standalone, in a
loop, from a nested switch, from default:, and in a value-returning function, against go run).
A user label on an empty statement emits an explicit empty statement
A Go label can attach to an empty statement — keep: as the last line of a block, a
goto/break/continue target with nothing between the label and the closing brace
(internal/trace gc.go’s goto keep target at the tail of a for-loop body). A C# label must
precede a statement, so a bare keep: before } is CS1525/CS1002. visitLabeledStmt detects
an *ast.EmptyStmt target and emits the explicit empty statement keep:; — the same shape the
break_<label>:;/continue_<label>:; synthesis already uses. A label on a non-empty statement
keeps the plain form (big: followed by its statement stays bare). Guarded by LabeledEmptyStmt (a
goto to an end-of-loop-body label, a goto to an end-of-function label, and a goto to an
end-of-inner-block label — values vs Go).
Reassigned or ref-bound range variable
A C# foreach iteration variable is read-only, but Go lets a range key/value variable be reassigned inside the body (it is a per-iteration copy). When the converter detects such a reassignment (=, +=, -=, ++, …) of a newly-:=-defined range variable — or a pointer-receiver method selected on the value-typed range var (q.GoString(), whose emitted form takes this ref T; a foreach var cannot bind ref — CS1657, dnsmessage’s four Message.GoString loops) — it iterates a temp and declares the variable as a mutable local copy in the body, rather than binding it directly. The per-iteration var q = vᴛ1; copy preserves Go’s semantics exactly: the pointer-receiver mutates the copy, as Go’s implicit (&q) on the range copy does. A pointer-typed range var is excluded (it dereferences; no ref bind), as are value-receiver and interface-method selections. The machinery covers string AND slice/array/map ranges:
for _, r := range s { // r is a rune
if r >= 0x10000 {
r -= 0x10000 // reassigns the range variable — CS1656 on a foreach var
…
}
}
foreach (var (_, rᴛ1) in s) {
var r = rᴛ1; // mutable local copy
if (r >= 0x10000) {
r -= 0x10000;
…
}
}
A range variable that is only read keeps binding directly to the foreach tuple (no temp, no churn). This reuses the same temp-var/innerPrefix machinery as the for k, v = range (re-assign-into-existing-vars) form. (Guarded by the RangeVarReassign behavioral test; runtime hits this in os_windows’s UTF-16 surrogate-pair encoder.)
Addressability flows from the path ROOT, not the immediate operand. Each trigger above is
matched against the identifier at the root of a field/element access path (rangeVarRootIdent),
because Go’s addressability propagates through every value hop: test.x.String() with a
pointer-receiver String is legal in Go (it auto-takes &test.x), and C# names the same rule in
its diagnostics — CS1654/CS1655 speak of “fields of” the iteration variable. Matching only the
immediate operand missed the whole class, which matters far beyond one construct because this is
the table-driven test idiom that dominates the standard library’s own test suites:
for _, test := range tests {
fmt.Println(test.x.String()) // pointer receiver on a FIELD of the range var — CS1655
}
foreach (var (_, vᴛ1) in range(tests)) {
var test = vᴛ1; // mutable, addressable per-iteration copy
fmt.Println(test.x.String());
}
The same root walk covers a write through a nested path (test.x.n = 99, CS1654) and an address
taken of one (&test.x). The walk stops at the first pointer hop: past a pointer the access
goes through the heap box (ж<T>.Value), an independent mutable lvalue the iteration variable’s
read-only-ness never reaches — so test.ptr.Bump() keeps the direct foreach binding with no copy,
and (matching Go) its write is observed by the source. Indexing likewise only continues through an
array, whose storage is in-place; a slice or map index reaches a separate backing store and is
its own addressability root. The copy is per-iteration, matching Go 1.22+ loop-variable semantics
(see For-clause variables are per-iteration).
Scoping the trigger to the root also keeps copies out where none is needed: a write like s.Name = x
through a pointer-typed range variable stops at the pointer hop and binds the foreach variable
directly. In the converted standard library the root walk’s copies appear in test code (the
table-driven idiom), not in production sources.
For-clause variables are per-iteration (Go 1.22 loop-variable semantics)
Go 1.22 gives each iteration of a for i := …; cond; post loop its own copy of the clause-declared variables, initialized from the previous iteration’s final value. A C# for-clause variable is ONE variable shared by every iteration, so a closure captured in the body would observe the shared post-mutated final value (3 3 3 instead of Go’s 0 1 2), and a stored &i would alias one shared box — compiling code that is silently wrong. When a clause-declared variable is captured by a func literal in the body or is heap-boxed, the converter rewrites the clause to drive a renamed carrier (iᴛ1) and re-declares the real variable fresh from the carrier at the top of the body; when the body can write the variable, its value is copied back to the carrier at every transfer to the post clause — the end of the body, before an unlabeled continue (a C# continue skips the end of the body), and after the continue_<label>: target (which the copy-backs deliberately follow, so a goto continue_<label> flows through them):
var fs []func() int
for i := 0; i < 3; i++ {
fs = append(fs, func() int { return i })
}
fmt.Println(fs[0](), fs[1](), fs[2]()) // Go 1.22+: 0 1 2
for (nint iᴛ1 = 0; iᴛ1 < 3; iᴛ1++) {
var i = iᴛ1;
fs = append(fs, [GoFunc("g1.func1")] () => i);
}
var i = iᴛ1; is a fresh variable each pass, so each closure captures its own.
A variable the body (or a closure in it) writes adds the copy-backs:
for (nint iᴛ1 = 0; iᴛ1 < 6; iᴛ1++) {
var i = iᴛ1;
if (i % 2 == 0) {
iᴛ1 = i;
continue;
}
i++;
fs = append(fs, [GoFunc("g2.func1")] () => i);
iᴛ1 = i;
}
An unlabeled continue copies back at its own site, and the copy-back at the end of the body feeds the post clause. A write is an assignment to the variable or to a field or element of it, or a call of a pointer-receiver method on it or on a value field of it, through parentheses too (c.inc(), (c).inc(), t.mid.in.inc(), (t.mid).in.inc()), so a struct clause variable changed by a method copies back too (the RangeVarWriteAfterCapture test’s clause rows).
A heap-boxed clause variable allocates a fresh box each pass — the same rule as the per-iteration range-variable box: a stored &i must be a distinct pointer per iteration — and always copies back (writes through the pointer are not syntactically detectable):
for (nint iᴛ1 = 0; iᴛ1 < 3; iᴛ1++) {
ref var i = ref heap<nint>(out var Ꮡi);
i = iᴛ1;
ps = append(ps, Ꮡi);
iᴛ1 = i;
}
The three stored pointers are distinct, and read 0 1 2.
Loops whose clause variables are neither captured nor boxed keep the plain C# clause — the shared clause variable is then unobservable, so there is no churn. A read-only captured variable skips the copy-backs; a write through the address of the variable’s element or value field (addTen(&a[1]), addTen(&c.n)), or through a slice of its array, is a write, so that variable keeps them. A clause variable that is an array, or a struct holding one, takes the value clone at both copies (var a = aᴛ1.Clone();, aᴛ1 = a.Clone();): the emitted value shares its backing, so plain copies would leave every iteration and every closure on one storage; a type parameter’s value takes ΔCopy() at both, and an element or element field write through it (a[1] += 10, a[1].n += 10) or its element’s address (addTen(&a[1])) counts as a write of the variable, so the copy back is written (guarded by ArrayCopyAliasSites, its for-clause row, and GenericBodyArrayCopies). Every clause reference (init/cond/post) renders the carrier, so the body keeps the variable’s Go name — nested same-name loops compose with shadow renames (iΔ1 gets carrier iΔ1ᴛ1), and a multi-variable clause transforms only the variables that need it. One fallback: a heap-boxed variable that a clause func literal references keeps a single box hoisted over the whole loop, since the body-scoped box would not be in scope at the clause. A struct variable that a literal in the condition reads does not yet compile in this fallback (Known issues). (Guarded by the ForLoopPerIterationVars behavioral test — read-only capture, body write + unlabeled continue, stored &i distinctness, boxed + captured closures, labeled continue with a write, nested same-name loops, a multi-variable clause, a struct-typed clause variable, an immediately-invoked writing closure, and element and field address writes — values vs Go. The EscapedLoopVarSiblingIndex and RingPointerMethods goldens also carry the per-iteration shape.)
The capture that has no func literal: defer/go on an indexed receiver
The trigger above asks whether a clause variable is heap-boxed or referenced inside a func literal
in the Go source. A defer/go statement can capture one with no func literal present at all:
visitDeferStmt/visitGoStmt SYNTHESIZE a lambda (() => recv.M()) for every callee the
method-group form cannot express – a result-returning method, a named func type
(context.CancelFunc), a variadic callee – and that synthesis happens long after the analysis has
run. Left SHARED, the clause variable would be read by the synthesized lambda at its post-loop value:
the capture snapshot (cʗ1) hoists the ARRAY, but the SUBSCRIPT is read when the defer fires, c[3].
deferOrGoCalleeReferences therefore joins the trigger, and the emission takes the ordinary
per-iteration shape above. The receiver itself is evaluated at the defer statement, as Go evaluates it:
the element cʗ1[i] is the thunk’s first eager argument (ᴛ0), so a later c[i] = other does not change
what is closed. An array copy shares its elements, so reading cʗ1[i] inside the thunk would see that
write.
var c [3]closer // Conn-shaped: Close() returns error
for i := 0; i < 3; i++ {
c[i] = dial(i)
defer c[i].Close() // Go: closes 2, 1, 0
}
for (nint iᴛ1 = 0; iᴛ1 < 3; iᴛ1++) {
var i = iᴛ1; // this iteration's own i
c[i] = dial(i);
var cʗ1 = c; // the capture snapshot of the array
defer(ᴛ0 => ᴛ0.Close(), cʗ1[i], ref ᒐ); // the element is read at the defer statement
}
net’s TestConcurrentSetDeadline is the witness: with the variable shared, defer c[i].Close() over a
[10]Conn indexes c[10] and panics with index out of range, a hard failure rather than a wrong answer.
Only the callee is consulted: a deferred call’s ARGUMENTS
are already evaluated at the defer statement exactly as Go requires
(defer((ᴛ1, ᴛ2) => f(ᴛ1, ᴛ2), a, i, ref ᒐ)), so a clause variable appearing only in an
argument needs no per-iteration copy – and minting one would move emission at every such site for
no behavioral gain. That restriction keeps the converted standard library’s production code
unchanged: its only sites with the shape (net/http/h2_bundle.go’s two
defer http2bufPools[index].Put(…) calls) index a plain local outside any loop. The shape occurs in
net/dial_test.go and net/timeout_test.go, so the rule reaches TEST conversions. (Guarded by the
DeferLoopCapture behavioral test: the defer witness and the go equivalent, an element reassigned after
a defer or go on it (interface, pointer and value elements, and a pointer method on a value element,
which Go binds by address and so does see the write), plus four controls – a receiver reassigned after
the defer, 3-clause and range closure capture, and deferred plain arguments – whose emission the trigger
must not move.)
A loop variable written after capture in the same iteration is shared
A closure in a loop body captures the iteration’s variable itself, not a copy of it. When the body writes that
variable after the closure is created, Go’s closure sees the write. The converter normally hands a captured loop
variable to the closure as a snapshot (var tʗ1 = t;), which is right while nothing writes it later in the same
iteration; a write after the closure would be lost to it. So a range or for-clause variable written after capture in
the same iteration takes shared storage, the same routing as
any variable written after capture: its
box, or a native C# capture when it has none.
var fs []func() int
for _, t := range []T{{1}, {2}} {
fs = append(fs, func() int { return t.n })
t.n += 10
}
fmt.Println("struct written after capture:", fs[0](), fs[1]()) // 11 12
internal static void structWrite() {
slice<Func<nint>> fs = default;
foreach (var (_, vᴛ1) in range(slice<T>([new(1), new(2)]))) {
ref var t = ref heap(new T(), out var Ꮡt);
t = vᴛ1;
fs = append(fs, [GoFunc("structWrite.func1")] () => Ꮡt.Value.n);
t.n += 10;
}
fmt.Println("struct written after capture:", fs[0](), fs[1]());
}
Sharing keeps Go’s per-iteration semantics because the C# storage is already per iteration: the box is allocated
inside the foreach body, once each pass (Reassigned or ref-bound range
variable), so each closure holds its own iteration’s box. A for-clause
variable captured in the body is redeclared from its carrier at the top of the body (For-clause variables are
per-iteration), and the copy-back at the end
of the body carries the write into the next iteration:
for t := (T{0}); t.n < 30; t.n++ {
fs = append(fs, func() int { return t.n })
t.n += 10
}
fmt.Println("for clause written after capture:", fs[0](), fs[1](), fs[2]()) // 10 21 32
internal static void clauseWrite() {
slice<Func<nint>> fs = default;
for (var tᴛ1 = (new T(0)); tᴛ1.n < 30; tᴛ1.n++) {
ref var t = ref heap<T>(out var Ꮡt);
t = tᴛ1;
fs = append(fs, [GoFunc("clauseWrite.func1")] () => Ꮡt.Value.n);
t.n += 10;
tᴛ1 = t;
}
fmt.Println("for clause written after capture:", fs[0](), fs[1](), fs[2]());
A write that runs after the closure counts when it comes later in the body, encloses the closure, sits in a loop
nested inside the body, is inside a func literal, or goes through an alias (&t, a pointer method called on t). A
write in a later pass of the defining loop does not count: it writes the next iteration’s variable. A write before the
closure, in the same iteration, keeps the snapshot, which then reads the written value:
foreach (var (_, vᴛ1) in range(slice<T>([new(1), new(2)]))) {
ref var t = ref heap(new T(), out var Ꮡt);
t = vᴛ1;
t.n += 10;
var tʗ1 = t;
fs = append(fs, [GoFunc("writeBefore.func1")] () => tʗ1.n);
}
The loop may itself sit inside a func literal: a goroutine body, a t.Run body, a handler. The literal that declares
the variable does not capture it, since each call of the literal has its own variable, so inside it the rule reads as
in a function body: only the closures nested in the loop body capture the variable, and a write at the literal’s own
level is ordered by position.
func([GoFunc("inLiteral.func1")] () => {
foreach (var (_, vᴛ1) in range(slice<T>([new(1), new(2)]))) {
ref var t = ref heap(new T(), out var Ꮡt);
Ꮡt.Value = vᴛ1;
Ꮡfs.ValueSlot = append(Ꮡfs.ValueSlot, [GoFunc("inLiteral.func1.1")] () => Ꮡt.Value.n);
Ꮡt.Value.n += 10;
}
})();
A literal in a for clause (the condition or the post statement) is left out: the clause sees one box hoisted over the whole loop, so such a variable keeps its snapshot. In a file before Go 1.22 the loop has one variable, which is shared whenever a closure captures it (below).
Guarded by: the RangeVarWriteAfterCapture behavioral test (struct, slice, map, pointer and interface range
variables written after capture, a pointer method after capture, an address stored and written through, deferred
closures, a goroutine, another closure that writes, a channel range, range over func, an int index, two for-clause
shapes, and the write-before and read-only near misses; and the same loops inside a func literal: a range in a
literal and in a goroutine body, another closure that writes, deferred closures, two for-clause loops over a struct,
a write before capture and a variable that is not a loop variable; output compared with Go). The
ForLoopPerIterationVars golden
carries the boxed form for a clause variable whose address is taken (p := &i).
A loop in a file before Go 1.22 has one variable per loop
Before Go 1.22 a for or range statement declares one variable for the whole loop, so a closure, a stored
address or a deferred closure sees the value the loop left in it. The rule follows the language version of the
loop’s own FILE: the module’s go line, raised or lowered by a //go:build go1.N line in that file, as go/types
records it in Info.FileVersions. A module with no go line is go1.16, the go command’s default. A standard
library file records no version and keeps per-iteration variables, as does a file loaded outside any module.
A three-clause loop keeps the plain C# for, whose clause variable is already shared, and none of the
per-iteration carrier machinery. A boxed
clause variable takes the box declared once before the loop (the same form as the clause-func-literal fallback), in a
block around the box and the loop, so that a sibling loop may reuse the name:
func threeClauseAddress() {
var ps []*int
for i := 0; i < 3; i++ {
ps = append(ps, &i)
}
fmt.Println("three-clause address:", *ps[0], *ps[1], *ps[2], ps[0] == ps[2])
}
internal static void threeClauseAddress() {
slice<ж<nint>> ps = default;
{
ref var i = ref heap<nint>(out var Ꮡi);
for (i = 0; i < 3; i++) {
ps = append(ps, Ꮡi);
}
}
fmt.Println("three-clause address:", ps[0].Value, ps[1].Value, ps[2].Value, ps[0] == ps[2]);
}
Go prints three-clause address: 3 3 3 true, and so does the C#.
A C# foreach declares its variables per iteration, so a range loop whose variable outlives an iteration (a body
func literal captures it, a defer or go callee is synthesized over it, or its address is taken) declares its
variables once, before the loop, and is emitted as the assigning form for k, v = range x (the
temp-and-copy machinery a reassigned range variable uses). A block around
the declarations and the loop keeps the names scoped to the loop, as Go scopes them, so a sibling loop may reuse a
name:
func rangeSliceAddress() {
var ps []*int
for _, v := range []int{7, 8, 9} {
ps = append(ps, &v)
}
fmt.Println("range slice address:", *ps[0], *ps[1], *ps[2], ps[0] == ps[2])
}
internal static void rangeSliceAddress() {
slice<ж<nint>> ps = default;
{
ref var v = ref heap(new nint(), out var Ꮡv);
foreach (var (_, vᴛ1) in range(slice<nint>([7, 8, 9]))) {
v = vᴛ1;
ps = append(ps, Ꮡv);
}
}
fmt.Println("range slice address:", ps[0].Value, ps[1].Value, ps[2].Value, ps[0] == ps[2]);
}
Go prints range slice address: 9 9 9 true, and so does the C#. Every non-blank variable of such a loop is
declared before it, because the assigning form assigns both. A range loop whose variables are neither captured nor
boxed emits as before: nothing can observe the difference. Range over an integer or a function needs go1.22 or
later, so it never takes this form.
A closure shares the loop’s one variable whatever its type. A captured variable that is only read would normally
be copied into the closure (var tʗ1 = t;, a snapshot that stands in for Go’s per-iteration variable), but here the
loop itself writes the variable on every pass, so the capture is routed to the shared storage instead: the box
(Ꮡt.Value; Ꮡp.ValueSlot for a pointer, whose box holds the pointer itself), or the C# variable itself when the
variable has no box. A struct element and a pointer clause variable:
fs = nil
for _, t := range []T{{1}, {2}} {
fs = append(fs, func() int { return t.n })
}
show("struct element", fs)
fs = default;
{
ref var t = ref heap(new T(), out var Ꮡt);
foreach (var (_, vᴛ6) in range(slice<T>([new(1), new(2)]))) {
t = vᴛ6;
fs = append(fs, [GoFunc("main.func8")] () => Ꮡt.Value.n);
}
}
show("struct element", fs);
fs = nil
for p := (&T{1}); p.n < 3; p = (&T{p.n + 1}) {
fs = append(fs, func() int { return p.n })
}
show("three-clause pointer", fs)
fs = default;
{
ref var p = ref heap<ж<T>>(out var Ꮡp);
for (p = (Ꮡ(new T(1))); p.n < 3; p = (Ꮡ(new T(p.n + 1)))) {
fs = append(fs, [GoFunc("main.func10")] () => Ꮡp.ValueSlot.n);
}
}
show("three-clause pointer", fs);
Go prints struct element: 2 2 and three-clause pointer: 3 3, and so does the C#. A closure that writes the
variable writes the loop’s variable, and a stored address and a capture see the same storage.
The same assigning form serves for x = range ch and for i = range n over a channel or an integer, which iterate
a temp and copy it in; a foreach declaring the variable’s own name would redeclare it.
Guarded by: LoopVarPreGo122 (a go 1.21 module: three-clause closure, address, body write and labeled
continue; deferred closures beside deferred arguments; a goroutine reading after the loop; range over a slice,
an array, a string, a map and a channel, captured and address-taken; a range body write; same-name sibling loops;
and a file raised to go1.22 by its build line, which keeps per-iteration variables and carries the assigning
channel and integer ranges), LoopVarNoGoLine (a module with no go line), and LoopVarPreGo122Captures (a
go 1.21 module: captures of a pointer, an interface, a slice, a map, a func, a struct and an error element; a
pointer three-clause variable; deferred and goroutine closures over a struct; an address stored beside a capture; a
boxed three-clause variable; a closure that writes; and a go1.22 file that keeps per-iteration variables).
A range-over-int index is nint (golib’s range helper yields Go’s int)
Go 1.22’s for i := range n (range over an integer) produces i of type int, which go2cs maps to nint. The converter lowers it to a foreach over golib’s range helper, and — with -var (the default) — leaves the index as the idiomatic var:
size := 5
var s []int
for i := range size {
s = append(s, i)
}
nint size = 5;
slice<nint> s = default;
foreach (var i in range(size)) {
s = append(s, i);
}
For var i to infer nint — matching Go’s index type — golib’s range(nint) must yield nint, not a C# int. An enumerator yielding int (such as Enumerable.Range(0, (int)n)) would make var i infer int, which is invisible until the index feeds a generic builtin: append(s, i) with s a slice<nint> and i an int matches two builtin.append overloads with different inferred T — append<T>(slice<T>, params Span<T>) infers T=nint (from s; the int→nint element conversion is implicit), while append<T>(ISlice, params T[]) infers T=int (from i). Neither wins the argument-by-argument betterness tie (each is better on one argument), so the call is ambiguous — CS0121. An explicit nint i always resolved (both overloads then infer T=nint, and slice<T> beats ISlice on the first argument), which is the tell that the problem lies in the element type the index infers, not the converter’s var (correct and idiomatic) nor the append overload set (unambiguous for a correctly-typed nint). The answer is therefore in golib: range(nint) yields nint. It returns golib’s RangeOverInt<nint> struct, whose struct enumerator yields 0..n-1 without allocating, and it matches Go’s integer-range semantics for n <= 0 exactly (zero iterations), where Enumerable.Range throws on a negative count. The maps and slices test suites (want = append(want, i) over a range(size) index) depend on exactly this. Guarded by the RangeIntIndexAppend behavioral test (the minimal append(s, i)-over-range(size) shape, output-compared vs Go; neutering golib’s range to IEnumerable<int> reproduces the CS0121).
Range-over-integer covers EVERY integer type, and the iteration variable keeps the operand’s width
Go 1.22’s range-over-integer accepts any integer type, not just int, and gives the iteration variable that type. The converter therefore treats every integer kind — uintptr, int64, uint8, rune, a named integer type — as a range-over-int operand. The stakes are silent: a range operand the converter does not recognize falls through visitRangeStmt’s unexpected 'ast.RangeStmt' expression arm, which prints the statement as a C# comment, so the loop does not fail to convert loudly, it vanishes, and the program quietly computes a different answer.
In the converted standard library, unique.buildArrayCloneSeq’s for range atyp.Len (unique/clone.go) is one,
where atyp.Len, an internal/abi field, is a uintptr:
for range atyp.Len {
switch etyp.Kind() {
case abi.String:
seq.stringOffsets = append(seq.stringOffsets, offset)
…
}
offset += etyp.Size()
}
foreach (var _ᴛ1 in range<uintptr>((~atyp).Len)) {
var exprᴛ1 = etyp.Kind();
if (exprᴛ1 == abi.String) {
seq.stringOffsets = append(seq.stringOffsets, offset);
}
…
offset += etyp.Size();
…
}
Commented out, the body would leave unique’s cloneSeq for any array-of-string type empty instead of carrying one offset per element. Non-int range operands are rare, which makes such a loss hard to notice.
Two pieces carry the rule. golib has a generic range<T>(T n), constrained to the operator pair the loop actually uses (IComparisonOperators<T,T,bool> + IIncrementOperators<T>, with default(T) for the zero) rather than IBinaryInteger<T> — golib’s own uintptr is a hand-written struct that implements the generic-math operator interfaces but not the INumberBase hierarchy, and uintptr is exactly the type this site ranges over. The converter then names T explicitly at every non-int site (range<uintptr>(…), range<rune>(…)), because Go’s rune and C#’s int are one CLR type and an inferred call could not tell for i := range r (yields rune) from for i := range 3 (yields Go’s int); a NAMED integer type is its own type argument with the operand passed through unchanged (range<myLen>(((myLen)3))), so the loop variable has the named type as in Go, and the converted /*num:…*/ struct binds because it declares the same operator interfaces.
The int case is emitted as bare range(expr), and it needs one guard of its own. A literal operand hands the overload set a C# int, where the generic is an identity match and range(nint) needs an implicit numeric conversion; the generic therefore wins outright and C#’s “a non-generic method is better than a generic method” tie-break never applies (measured, not reasoned: without the guard range(3) yields System.Int32). golib carries a third overload, range(int n) → RangeOverInt<nint>, meaning “a C# int operand is Go’s int”: an int-typed operand in emitted code can only be an untyped Go constant, since a Go int expression already renders as nint and every other width is emitted with an explicit type argument. With it, for i := range 3 stays on nint and the CS0121 above cannot come back.
Guarded by the RangeOverIntegerTypes behavioral test (blank-key uintptr, uint8/int64/uint64/rune, a named uintptr type, non-positive operands, and the unchanged int/untyped cases, output-compared vs Go — reverting the isInt widening reproduces FAIL [Target,Output]) and by GolibTests.GoStructLayoutTests (the range<T> widths and the literal-operand overload binding).
An index-only range over a slice or array reads no element
Go’s index-only range (for i := range s, for i, _ := range s, or for range s) reads the length once and
loads no element. The converter ranges the length, foreach (var i in range(len(s))), when the operand is a
slice, an array, a named slice or array type, a type parameter whose core type is one, or a variadic parameter
that the converter emits as golib’s stack-only sslice<T>:
for i := range s { … }
for range s { … }
foreach (var i in range(len(s))) { … }
foreach (var _ᴛ1 in range(len(s))) { … }
len(s) is evaluated once, when the loop starts, and the integer range returns RangeOverInt<nint>, the
allocation-free enumerator of range-over-int, so i is Go’s int and the loop yields 0 to len(s) - 1. A
package that declares its own len method (index/suffixarray’s func (a *ints) len() int) hides golib’s builtin
inside its package class, so there the converter spells range(builtin.len(s)).
The (index, value) enumerator, range(s), would not do here even with the value discarded: it reads every element
into a stack temp. An element the body waits to see collected stays reachable from the loop’s own frame
(crypto/internal/fips140cache’s TestCache waits for exactly that and would never finish), and an element of a
native-backed slice over memory that refuses a read panics where Go touches nothing.
The scalar escapes of range-over-int apply unchanged: a blank or absent key iterates a marked temp (see
A blank scalar range variable never emits as _), an assigned key (for i = range s) iterates a temp and copies it into the existing variable, a key the
body writes iterates a temp and declares the variable from it, and an address-taken key gets a fresh box per
iteration.
What keeps the pair form:
- a string,
foreach (var (i, _) in s), because its indexes are the byte offsets where each rune starts, which its length alone cannot produce; - a map,
foreach (var (k, _) in m); - a range with a value variable,
foreach (var (i, v) in range(s)).
Go’s length of a *[N]T is the constant N, so Go ranges a nil array pointer N times without dereferencing it.
golib’s array carries its length in the value, not the type, so only the converter knows N, and it passes it:
range(p, N) reads neither the pointer nor an element, and a nil p ranges N times. The pointer is still
evaluated once, as Go evaluates a range operand that holds a call.
A pointer parameter is already the dereferenced array, either its ref-lowered form or its DerefOrNull entry alias.
A pointer receiver is the value it addresses (this ref T b). Either would range a ref, which is null for a nil
pointer and faults where Go ranges N times. Neither needs evaluating, because with at most one iteration variable and
a constant length Go does not evaluate the range operand at all. So each ranges the count itself, range(N), a
pointer to a named array type included; the box overload, which cannot bind a ref (CS0411), is never asked to.
Guarded by the converter’s TestIndexOnlyRangeEmitsTheIndexEnumerator, which pins every operand kind above, the
scalar escapes and the string, map and value-variable controls, and a pointer to an array, a nil one, a pointer
parameter and a pointer receiver; by TestAnIndexOnlyRangeInAMethodOfATypeWithALenMethodReadsTheBuiltinBare (a method’s
body stands in the package class under its suffixed name, so a len method hides no built-in there); by
TestRangeOverPointerArrayValueIsCountRange, which pins the count range for a lowered parameter, an aliased one, a
named array and a receiver beside the box, value and slice controls; and by the behavioral goldens
ArrayRangeSnapshot, SlicePointerIdentity, VariadicPackPassThrough, PointerArraySlice, whose rangeIndexOnly
ranges a nil *[3]int and a nil *grid and prints Go’s counts, and whose fill ranges its pointer receiver, and
PointerArrayRange, which ranges a nil lowered parameter, a nil aliased one and a nil receiver.
A blank scalar range variable never emits as _
A range with no iteration variable (or an explicit blank) over a scalar-yield source — a channel, an integer (Go 1.22 for range n), a single-value yield function in the foreach form, or a slice or array (whose index-only range also lowers to range(len(x))) — needs a C# foreach iteration variable, and that variable must not be named _: in a scalar foreach position C# declares a genuine read-only variable named _ (only tuple-deconstruction _ is a discard), which shadows the discard idiom for the entire loop body. Any Go blank assignment inside the body (_ = f(x) — evaluate and discard) then resolves to that variable and becomes an illegal write to a foreach iteration variable (CS1656; first hit: encoding/binary’s BenchmarkSize, for range b.N { _ = Size(data) }). The converter emits a marked temp instead:
for range b.N {
_ = Size(data)
}
foreach (var _ᴛ1 in range((~bΔ1).N)) {
_ = Size(dataʗ1);
}
Tuple positions are unaffected — foreach (var (_, data) in …) keeps the true C# discard. A range-over-func loop
converted to a call of its iterator has no foreach variable: its body is a lambda that takes the value as a
parameter, (nint _) =>, which the body may assign.
Guarded by the RangeStatements behavioral test (blank int-range and blank channel-range, each with a body blank assignment; the compile phase is the guard — a _-named iteration variable is CS1656).
for range over a slice allocates NOTHING — range(s) and GetEnumerator() return structs
for i, v := range s emits foreach (var (i, v) in range(s)), and Go’s range over a slice allocates nothing at all. C# matches that only if the enumerator stays off the heap, which is entirely a question of what GetEnumerator returns: foreach binds GetEnumerator by pattern — the concrete return type, ahead of and independently of any interface — so a struct return is enumerated in place, while an interface return is a heap object per loop entry.
An interface return from an ITERATOR method (yield return) would be the worst of both: the compiler-generated state machine is one allocation and any inner enumerator class it drives is a second, two heap objects per loop entry in every ranged loop of every converted package, paid whether the loop body allocates or not. That is invisible in output and in timings at small scale, and unmissable in a Go test that asserts an allocation count: time.TestUnmarshalTextAllocations runs parseRFC3339, whose parseUint closure ranges its argument once per field.
So every enumerator on the path is a struct:
- golib’s
range(s)returnsslice<T>.RangeOver, a struct whoseGetEnumerator()returns theslice<T>.RangeEnumeratorstruct over Go’s(index, value)pairs;array<T>,sslice<T>and a pointer to an array have the same pair. slice<T>.GetEnumerator()returns the concrete nestedslice<T>.Enumeratorstruct over the values (the shapeList<T>.Enumeratoruses), soforeach (var v in s)in hand-written C# allocates nothing either.IEnumerable<T>is the only generic sequence interface a slice has, so LINQ sees the values; its member is an explicit implementation returning the same struct boxed, so an interface-typed local ranges at the cost of one box.- go2cs-gen’s
ISliceTypeTemplate(everytype S []Enamed-slice wrapper) forwardsglobal::go.slice<E>.Enumerator, so a named slice type enumerates as cheaply as theslice<E>it wraps. Its pair loop names the element type,range<E>(x), so the wrapper’s implicit conversion binds theslice<E>overload, which C#’s inference alone cannot reach through a conversion.
A named array type or a type parameter’s sequence ranges range(x) through IArray<T>, which reads the length and the indexer and boxes a struct operand once per loop. array<T>’s own pair enumerator works only because the copy Go’s array range takes is placed on the range expression; see the next section.
Guarded by SliceRangeAllocationTests and ArrayRangeAllocationTests in GolibTests, which assert zero bytes via GC.GetAllocatedBytesForCurrentThread across 1,000 loops of range(s) (whole slice, sub-window with window-relative indices, and the nil slice), plus the interface-path equivalence. It is a measured guard on purpose: an interface return type still compiles and still produces correct output — it just allocates — so only bytes can catch the regression. Neutering to the interface return, or to an iterator body, makes it report a nonzero per-loop byte count.
range over an ARRAY VALUE iterates a COPY — the snapshot is the range EXPRESSION’s ΔRangeSnapshot()
Go evaluates a range expression once before the loop, so for i, v := range a over an array VALUE iterates a copy: a write to the container inside the body is invisible to every later iteration. The emitted array<T> (and the generated named-array wrapper) is a struct over a shared T[] backing, so a plain operand would ALIAS the container and read the writes back, diverging from go run on every such loop:
a := [4]int{1, 2, 3, 4}
for i, v := range a {
if i == 0 { a[1], a[2], a[3] = 91, 92, 93 }
fmt.Println(i, v) // Go: 1 2 3 4 an aliased operand: 1 91 92 93
}
The range expression is therefore an array value-copy site of its own (see Array VALUE-COPY at every transfer site, whose range entry covers the iteration VARIABLE, not the operand):
foreach (var (i, v) in range(a.ΔRangeSnapshot())) { … } // array value — snapshot, Go's copy
foreach (var (i, v) in range(h.arr.ΔRangeSnapshot())) { … } // struct field — likewise a value
foreach (var (i, v) in range(r.ΔRangeSnapshot())) { … } // named array — the wrapper forwards it
Why it is not the .Clone() every other transfer site takes, and this is the load-bearing part.
Semantically it could be. But a Go array copy lives INLINE — on the stack when the
destination is a local — so Go charges it zero mallocs and zero TotalAlloc, and a range snapshot
is the one array copy that provably cannot outlive its statement. Clone() mints a counted managed
array through AllocationCounter, which is right for a copy that DOES outlive the statement (an
assignment, a return, a field, a channel send) and wrong for one that cannot: golib’s counter is
documented as the structural mirror of runtime.MemStats.Mallocs, so charging what Go does not
makes the mirror wrong by construction, and every testing.AllocsPerRun assertion around a range
over an array value would disagree with Go’s own number. The byte meter is stricter still —
runtime.ReadMemStats’s TotalAlloc maps to GC.GetTotalAllocatedBytes, which no counter can hide
from — so the copy has to genuinely not allocate. array<T>.ΔRangeSnapshot() returns a RangeSnapshot
struct whose enumerator rents from ArrayPool<T>.Shared and returns the buffer in Dispose, which
C#’s foreach calls in a finally; steady state is zero managed allocations on both meters. Three
residuals are named rather than hidden: the first rent of a size class allocates once per process, an
array beyond the pool’s largest bucket allocates per rent (as it would in Go, which also moves an
array that size off the stack), and an element type needing a DEEP copy still allocates per element,
because a nested array<T>’s backing is a heap object in this model.
A SLICE element is never re-copied, and re-copying one crashes. array<T>.Clone()
re-clones elements that are themselves array wrappers, and ISlice<T> derives from IArray<T> — so a
named-slice element passed that test, while the generated wrapper’s Clone() forwards to the
underlying slice<T>’s ICloneable.Clone(), which hands back a boxed slice<T>: the element cast is
then slice<int> → ΔBits and throws InvalidCastException. The range snapshot is a caller that
clones an array whose element is a slice: math/big’s bitsList ([...]Bits, type Bits []int) is the
one in the converted standard library, which TestFloatAdd and TestFloatMul exercise. Semantically the exclusion is required anyway: Go’s
array-of-slices copy copies HEADERS and
shares every backing store, which the shallow element copy does. The ArrayRangeSnapshot
guard pins both halves — replacing a whole element through the original is invisible to the loop
(a fresh header), while a write THROUGH a shared backing is visible.
Scoped exactly as gc’s own rule is (cmd/compile/internal/walk/order.go’s rangeStmt), so three shapes stay UNCOPIED because Go copies nothing there either — and each is a control in the guard:
- No value iteration variable. With at most one iteration variable and a constant length, Go does not evaluate the range expression at all, so
for i := range areads the LIVE array through the index. It emitsforeach (var i in range(a)), whose golib overload readslen(a)once and never an element. A blank value (for i, _ := range a) is the same case. - A POINTER to an array.
for i, v := range pshares the pointee; the emission keeps the barep.Value. - A slice. Its copy is the header, which the struct assignment already is.
exprReadsValueNeedingClone narrows the rest: only a read out of EXISTING storage (ident, selector, index, deref) can alias — a composite literal, call result, or conversion is freshly constructed and reachable by no other name, and a return already clones on its own way out.
With the operand snapshotted, array<T>’s enumerator reads LIVE storage and needs no capture point of its own, so it needs no iterator method: GetEnumerator() returns the nested array<T>.Enumerator STRUCT, and go2cs-gen’s IArrayTypeTemplate / IArrayViewTypeTemplate forward that struct (with the explicit IArray<T>.GetEnumerator() member beside it) so named array types range as cheaply. Measured with GC.GetAllocatedBytesForCurrentThread over 1,000 loops, the pattern path costs zero bytes, and the boxing interface path costs one boxed struct rather than an iterator state machine. Snapshotting inside the enumerator instead would be wrong in both directions — it would allocate on every loop AND copy for the two shapes above where Go shares.
Guarded two ways: ArrayRangeSnapshot (behavioral, output-compared against go run) mutates the container mid-loop across the array value, named-array, struct-field, nested-array, array-of-named-slices, =-form, mutable-range-var and aliased-element shapes, with the pointer, slice and index-only arms as controls that must NOT copy; ArrayRangeAllocationTests (GolibTests) asserts the enumerator’s zero bytes with the boxing interface path as its nonzero control, the snapshot’s zero on BOTH meters (object count and CLR bytes) with Clone() as the counted control that makes those zeros mean something, and the array-of-slices copy that must share its backing rather than throw.
A range-over-func loop converts to a call of its iterator
for k, v := range seq { body } converts to seq((k, v) => { body }): the loop is a call of the iterator, and
the loop body is the lambda the iterator receives as yield. Go’s own compiler lowers the statement the same
way (cmd/compile/internal/rangefunc/rewrite.go), so the body runs on the ranging goroutine and the iterator
runs as an ordinary call.
func closuresInBody() int {
var fs []func() int
total := 0
for i := range count(3) {
for j := range count(2) {
fs = append(fs, func() int { return i*10 + j })
}
}
for _, f := range fs {
total += f()
}
return total
}
internal static nint closuresInBody() {
ref var fs = ref heap<slice<Func<nint>>>(out var Ꮡfs);
nint total = 0;
// for i := range count(3)
var seqᴛ1 = count(3);
var rangeᴛ1 = new golib.RangeFuncState();
seqᴛ1([GoFunc("closuresInBody-range1")] (nint i) => {
rangeᴛ1.Enter();
// for j := range count(2)
var seqᴛ2 = count(2);
var rangeᴛ2 = new golib.RangeFuncState();
seqᴛ2([GoFunc("closuresInBody-range2")] (nint j) => {
rangeᴛ2.Enter();
Ꮡfs.ValueSlot = append(Ꮡfs.ValueSlot, [GoFunc("closuresInBody.func1")] () => i * 10 + j);
return rangeᴛ2.Continue();
});
rangeᴛ2.Exit();
return rangeᴛ1.Continue();
});
rangeᴛ1.Exit();
foreach (var (_, f) in range(fs)) {
total += f();
}
return total;
}
What the converter writes for one loop, in order:
// for … range …: the Goforclause as a comment, so a reader can find the loop.var seqᴛN = <range expression>;: Go evaluates the range expression once, before the first call of the body. The line is left out when the range expression is already a name, which is then called directly.var rangeᴛN = new golib.RangeFuncState();: the loop’s state, Go’s#statevariable. It is declared where the loop stood, so a loop inside another loop’s body gets a new state on each pass, asrangeᴛ2does above.- The call. The lambda’s parameters are the loop’s variables. A value the loop does not name, or names
_, is a discard parameter (_, or_Δp0and_Δp1when there are two). In the=form (for i, s = range seq) the parameters arepᴛ1andpᴛ2, and the body starts with the assignment(i, s) = (pᴛ1, pᴛ2);. The assignment targets may be any assignable expression. rangeᴛN.Enter();as the body’s first statement.return rangeᴛN.Continue();where the body ends and for eachcontinueof this loop;return rangeᴛN.Break();for eachbreakof this loop. Abreakorcontinuethat belongs to afor,switchorselectinside the body is not changed.rangeᴛN.Exit();after the call.
The numbers in seqᴛN, rangeᴛN and nextᴛN count per function.
The state type. RangeFuncState holds one of Go’s four
loop states and makes the checks Go’s lowering makes. Enter() reads the state, marks the body as running, and
panics if the body may not run. Continue() marks the loop ready and answers true. Break() marks the loop
done and answers false. Exit() panics if the body is still marked as running, and otherwise marks the loop as
over. The four panics are runtime errors with Go’s texts:
| When | Text |
|---|---|
yield is called after it answered false |
range function continued iteration after function for loop body returned false |
yield is called after the body panicked |
range function continued iteration after loop body panic |
yield is called after the iterator returned |
range function continued iteration after whole loop exit |
| the iterator recovers a panic of the body and returns | range function recovered a loop body panic and did not resume panicking |
Enter() writes the running mark before it panics, as Go does, so a second late call of yield reports
after loop body panic. The type is a struct that is not a ref struct and has no readonly members: the
lambda captures the local, and each call must write the same variable. Converted code names the type only in
that declaration.
The body is a function literal to every analysis. The loop is rewritten on the syntax tree before the
converter’s analyses run, so captures follow the rules for a Go closure. In the example, fs is a slice local
that a lambda appends to, so it lives in a heap box and the body writes it through Ꮡfs.ValueSlot. A loop
variable declared by := is a parameter of the lambda, which gives each pass its own variable, as Go requires.
One rule of a loop body stays: Go declares the loop’s variables in the loop statement’s scope, one scope outside
the body, so a declaration in the body that uses a loop variable’s name (v, odd := f(v), or var v float64)
is a new variable. It takes a Δ name, as any shadowing declaration does (redeclare and redeclareVar in
RangeFuncLoweredShapes). In an ordinary function literal the same := assigns to the parameter.
A pointer receiver the body uses takes the box form. A lambda cannot capture a ref parameter, so a method
whose pointer receiver is used in a converted loop body takes its receiver as the box, as a method with any
capturing function literal does: Result⁔(ж<ResponseRecorder> Ꮡrw) in net/http/httptest, where the receiver
was ref ResponseRecorder rw. For an exported method this is a change of public surface. The method holder
keeps the ж<T> form of the method and loses the ref T form, so a caller that held the struct by value and
called the method on it must call it through a pointer. (*ResponseRecorder).Result in the
standard library is an example.
The body’s Go name. Go names the body function <outer>-range<N>, counting the range-over-func bodies of the
outer function from 1 in source order, a nested body after the body that holds it. A loop that keeps the foreach
form (below) takes its number too, as in Go, so a converted body after it or inside it keeps Go’s number.
[GoFunc(…)] records that name. A function literal inside a body is numbered as if it stood in the outer function
(closuresInBody.func1 above), which is also Go’s rule, and a loop inside a literal is named for the literal
(f.func4-range1), as a loop in a method is for the method ((*walker).walk-range1). runtime.Caller and
runtime.FuncForPC read the name from inside the body, as in Go.
Why. The foreach form runs the iterator on a second goroutine and hands each value across with two
goroutine switches. The call form runs no second goroutine, and it is the form Go’s compiler produces, so the
order of side effects, the goroutine that runs the body, and the panics for a misused yield are Go’s.
Limits. These loops keep the foreach form:
- a loop with a
deferin its body, or a body that can block; a comment names the reason (the rule below); - a loop whose body calls
recover(), which answers for the function it is written in; - a loop whose range expression is a function literal, or has a type parameter’s type;
- a loop whose body returns results from a function with a result named
_.
A kept loop’s body runs in the enclosing function’s frame, so runtime.Caller inside it reports the enclosing
function, where Go reports <outer>-range<N>.
Guarded by: RangeFuncOracle (Go’s own rangefunc_test.go as a program, output compared with Go),
RangeFuncLoweredShapes, RangeFuncLoweredCaptures and RangeFuncLoweredJumps (behavioral, output compared
with Go), RangeFuncFrameNames (behavioral, output compared with Go: the name runtime.FuncForPC reads in
thirteen places, the function, its literals, nested and sibling bodies, a loop in a literal, a loop in a method,
a loop after a kept loop and inside one, and a loop after ranges over an int, a slice and a channel),
GenericTypeInference, ProxyContainerForwarding and SelectStatement (goldens), the converter unit test
TestRangeOverFuncLoweringDecision, and GolibTests RangeFuncStateTests and RuntimeErrorClassesTests.
A return in a range-over-func body stores the results and returns after the call
The body is a lambda whose result is yield’s bool, so a return in the body cannot return from the
enclosing function. The converter writes what Go’s lowering writes: the body stores the results, sets
nextᴛN = -1, and returns rangeᴛN.Break(). After rangeᴛN.Exit(), if (nextᴛN == -1) returns from the
function.
func find2(n int, want int) (int, string) {
for i, s := range pairs(n) {
if i == want {
return i, s
}
}
return -1, ""
}
internal static (nint, @string) find2(nint n, nint want) {
nint retᴛ1 = default;
@string retᴛ2 = default;
// for i, s := range pairs(n)
var seqᴛ1 = pairs(n);
var rangeᴛ1 = new golib.RangeFuncState();
nint nextᴛ1 = default;
seqᴛ1([GoFunc("find2-range1")] (nint i, @string s) => {
rangeᴛ1.Enter();
if (i == want) {
(retᴛ1, retᴛ2) = (i, s);
nextᴛ1 = -1;
return rangeᴛ1.Break();
}
return rangeᴛ1.Continue();
});
rangeᴛ1.Exit();
if (nextᴛ1 == -1) {
return (retᴛ1, retᴛ2);
}
return (-1, "");
}
Where the results are stored. A function with unnamed results gets one retᴛN variable per result,
declared at the top of the function body and shared by every loop of the function. A function whose results
are all named needs none: the body assigns the named results, and the exit after the call returns them. A
return with no results, in a function with no results or with named ones, only sets nextᴛN.
Nested loops share one nextᴛN. It is declared for the outermost converted loop, and only when that loop’s
body, or a converted loop inside it, has a return or
a jump out of the body.
After an inner loop’s Exit(), the outer body tests it and leaves in turn:
if (nextᴛ1 == -1) { return rangeᴛ1.Break(); }.
In a function with a defer, the retᴛN variables are declared ahead of the frame. Such a function’s body
is a try block, and the arm that handles a recovered panic returns the function’s results. A panic can
arrive after the body stored its results, so that arm returns the retᴛN variables:
func g() string {
defer func() { recover() }()
for s := range terrify("g panic", once("g return")) {
return s
}
return "g not reached"
}
internal static @string g() { @string retᴛ1 = default; GoFrame ᒐ = default; try {
defer([GoFunc("g.func1")] () => {
recover();
}, ref ᒐ);
// for s := range terrify("g panic", once("g return"))
var seqᴛ1 = terrify<@string>("g panic", once<@string>(gReturnˢ));
var rangeᴛ1 = new golib.RangeFuncState();
nint nextᴛ1 = default;
seqᴛ1([GoFunc("g-range1")] (@string s) => {
rangeᴛ1.Enter();
retᴛ1 = s;
nextᴛ1 = -1;
return rangeᴛ1.Break();
});
rangeᴛ1.Exit();
if (nextᴛ1 == -1) {
return retᴛ1;
}
return "g not reached";
} catch (Exception ᒐe) when (ᒐ.Is(ᒐe)) { ᒐ.Capture(); return retᴛ1; } finally { ᒐ.Run(); } }
gReturnˢ is the hoisted string literal "g return". Here terrify panics after the body returned, the
deferred function recovers the panic, and g returns "g return", as it does in Go.
Limits. A function with a result named _, such as (n int, _ error), has no single place for the
stored results. A loop in such a function whose body returns results keeps the foreach form.
Guarded by: RangeFuncLoweredShapes (find, find2), RangeFuncLoweredCaptures (inLiteral, a return from
a loop inside a function literal; nested in RangeFuncLoweredShapes returns through two loops) and
RangeFuncOracle (g, h, j, k, m, n), all output compared with Go.
A jump out of a range-over-func body stores a code and is finished after the call
A goto, or a break or continue with a label, can name a place outside the loop body. The body is a
lambda, so the jump cannot be written there. The converter writes what Go’s lowering writes: the body stores a
code for the jump in nextᴛN and returns rangeᴛN.Break(), which stops the iterator. After
rangeᴛN.Exit() a test of the code finishes the jump, or passes it to the loop outside.
A break or continue of a converted loop further out. The converted loops of a nest are numbered from 1
at the outermost. continue of loop N is code 2N-1 and break of loop N is code 2N. The loop the jump
names tests its code after the inner call, sets nextᴛN back to 0, and returns Continue() or Break():
func continueOuter(n int) []int {
var seen []int
Outer:
for i := range count(n) {
for j := range count(n) {
if j > i {
continue Outer
}
seen = append(seen, i*10+j)
}
seen = append(seen, -i)
}
return seen
}
internal static slice<nint> continueOuter(nint n) {
ref var seen = ref heap<slice<nint>>(out var Ꮡseen);
// Outer: for i := range count(n)
var seqᴛ1 = count(n);
var rangeᴛ1 = new golib.RangeFuncState();
nint nextᴛ1 = default;
seqᴛ1([GoFunc("continueOuter-range1")] (nint i) => {
rangeᴛ1.Enter();
// for j := range count(n)
var seqᴛ2 = count(n);
var rangeᴛ2 = new golib.RangeFuncState();
seqᴛ2([GoFunc("continueOuter-range2")] (nint j) => {
rangeᴛ2.Enter();
if (j > i) {
nextᴛ1 = 1;
return rangeᴛ2.Break();
}
Ꮡseen.ValueSlot = append(Ꮡseen.ValueSlot, i * 10 + j);
return rangeᴛ2.Continue();
});
rangeᴛ2.Exit();
if (nextᴛ1 == 1) {
nextᴛ1 = 0;
return rangeᴛ1.Continue();
}
Ꮡseen.ValueSlot = append(Ꮡseen.ValueSlot, -i);
return rangeᴛ1.Continue();
});
rangeᴛ1.Exit();
return seen;
}
The label Outer is not written. Every break and continue that named it is now a stored code, so nothing in
the C# can name it. The comment above the converted loop keeps the name.
A jump to any other label. Each label of the function has three codes, by its place in the function counted
from 1: -1 - 3k for a break, -3k for a continue and 1 - 3k for a goto (code -1 is a return). Each
converted loop the jump crosses tests nextᴛN < 0 after the inner call and returns Break(). After the
outermost converted loop the jump crosses, the code is tested and the jump is written as it would be outside a
body: goto L for a goto, and goto break_L or goto continue_L for a labeled break or continue of an
ordinary loop:
func gotoOut(n int) (found string) {
for i := range count(n) {
for j := range count(n) {
if i*j == 6 {
found = fmt.Sprint(i, "x", j)
goto Done
}
}
}
found = "none"
Done:
return found + "!"
}
internal static @string /*found*/ gotoOut(nint n) {
@string found = default;
// for i := range count(n)
var seqᴛ1 = count(n);
var rangeᴛ1 = new golib.RangeFuncState();
nint nextᴛ1 = default;
seqᴛ1([GoFunc("gotoOut-range1")] (nint i) => {
rangeᴛ1.Enter();
// for j := range count(n)
var seqᴛ2 = count(n);
var rangeᴛ2 = new golib.RangeFuncState();
seqᴛ2([GoFunc("gotoOut-range2")] (nint j) => {
rangeᴛ2.Enter();
if (i * j == 6) {
found = fmt.Sprint(i, "x", j);
nextᴛ1 = -2;
return rangeᴛ2.Break();
}
return rangeᴛ2.Continue();
});
rangeᴛ2.Exit();
if (nextᴛ1 < 0) {
return rangeᴛ1.Break();
}
return rangeᴛ1.Continue();
});
rangeᴛ1.Exit();
if (nextᴛ1 == -2) {
nextᴛ1 = 0;
goto Done;
}
found = "none";
Done:
return found + "!"u8;
}
Done is the function’s only label, so its goto is code 1 - 3 = -2.
A goto to the loop’s own label. Go runs the loop statement again. The label stays, on a block that holds
the converted loop, and the test after Exit() jumps to it:
func restart(n int) []int {
var seen []int
rounds := 0
Again:
for i := range count(n) {
seen = append(seen, i)
if i == 1 && rounds < 2 {
rounds++
goto Again
}
}
return seen
}
internal static slice<nint> restart(nint n) {
ref var seen = ref heap<slice<nint>>(out var Ꮡseen);
nint rounds = 0;
Again:
{
// for i := range count(n)
var seqᴛ1 = count(n);
var rangeᴛ1 = new golib.RangeFuncState();
nint nextᴛ1 = default;
seqᴛ1([GoFunc("restart-range1")] (nint i) => {
rangeᴛ1.Enter();
Ꮡseen.ValueSlot = append(Ꮡseen.ValueSlot, i);
if (i == 1 && rounds < 2) {
rounds++;
nextᴛ1 = -2;
return rangeᴛ1.Break();
}
return rangeᴛ1.Continue();
});
rangeᴛ1.Exit();
if (nextᴛ1 == -2) {
nextᴛ1 = 0;
goto Again;
}
}
return seen;
}
A nest that mixes the two forms. A loop that keeps the foreach form (the next rule) can hold a converted
loop, or stand inside one. A converted loop inside a kept loop reaches the kept loop’s label as it reaches any
other label: a negative code, then goto continue_L or goto break_L after the outermost converted loop, in the
body of the foreach:
func keptOuter(n int) (seen []int) {
Outer:
for i := range count(n) {
defer func() { seen = append(seen, -100-i) }()
for j := range count(n) {
if j > i {
continue Outer
}
if i == 2 {
break Outer
}
seen = append(seen, i*10+j)
}
seen = append(seen, -i)
}
seen = append(seen, 1000)
return seen
}
internal static slice<nint> /*seen*/ keptOuter(nint n) { slice<nint> seen = default; GoFrame ᒐ = default; try {
Outer:
// range over func on a coroutine: defer in body
foreach (var i in range<nint>(count(n).Invoke)) {
defer([GoFunc("keptOuter.func1")] () => {
seen = append(seen, -100 - i);
}, ref ᒐ);
// for j := range count(n)
var seqᴛ1 = count(n);
var rangeᴛ1 = new golib.RangeFuncState();
nint nextᴛ1 = default;
seqᴛ1([GoFunc("keptOuter-range2")] (nint j) => {
rangeᴛ1.Enter();
if (j > i) {
nextᴛ1 = -3;
return rangeᴛ1.Break();
}
if (i == 2) {
nextᴛ1 = -4;
return rangeᴛ1.Break();
}
seen = append(seen, i * 10 + j);
return rangeᴛ1.Continue();
});
rangeᴛ1.Exit();
if (nextᴛ1 == -3) {
nextᴛ1 = 0;
goto continue_Outer;
}
if (nextᴛ1 == -4) {
nextᴛ1 = 0;
goto break_Outer;
}
seen = append(seen, -i);
continue_Outer:;
}
break_Outer:;
seen = append(seen, (nint)1000);
} catch (Exception ᒐe) when (ᒐ.Is(ᒐe)) { ᒐ.Capture(); } finally { ᒐ.Run(); } return seen; }
A kept loop inside a converted body is an ordinary statement of the lambda. A continue or break of the
converted loop from inside it is return rangeᴛN.Continue() or return rangeᴛN.Break(), written in the body of
the foreach. Returning from a foreach disposes its enumerator, which stops the kept loop’s iterator and runs
that iterator’s deferred calls. A jump further out from there stores its code first, as in any converted body.
What stays as written. A jump whose label is declared inside the body is an ordinary jump of the lambda and
is not changed. A labeled break or continue that names the converted loop the statement is directly in is
that loop’s own Break() or Continue(). A nest in which the only exit is a return keeps the test
nextᴛN == -1; the wider nextᴛN < 0 is written only where another negative code can cross.
Why. These are the codes and the tests of Go’s compiler (cmd/compile/internal/rangefunc/rewrite.go), so a
jump stops each iterator it leaves in Go’s order, from the innermost out, and an iterator that calls yield
again after the body asked it to stop panics as it does in Go.
Limits. Go’s lowering also writes if #next > 2*N { panic } after a nested call in the body of loop N, to
catch a code that names a loop further in. The converter does not write it. In a program without a data race,
the test of the loop a code names clears the code, or one of the state checks ends the path, before control
reaches that point. A program that calls yield from two goroutines with no synchronization can reach it: Go’s
check can fire there, and the converted nest ends as a break.
Guarded by: RangeFuncLoweredJumps (behavioral, output compared with Go: breakOuter, continueOuter,
threeDeep, gotoOut, gotoBack, restart, plainLoops, inBody, local, mixed, both, innerAgain,
and the nests that mix the two forms, keptOuter, keptInner and threeMixed), RangeFuncOracle
(Go’s own tests of labeled jumps out of nested iterators, TestPanickyIterator2, TestPanickyIterator3,
TestVeryBad1 and TestVeryBad2 among them) and the converter unit test TestRangeOverFuncLoweringDecision
(jumping).
A range-over-func loop with a defer or a body that can block keeps the foreach form
Two kinds of loop are not converted to a call. Each stays a foreach over golib’s range helper, which runs
the iterator on a second goroutine, and each gets a comment that names the reason:
func keptDefer() (out []int) {
for v := range count(3) {
defer func() { out = append(out, v) }()
}
return
}
internal static slice<nint> /*out*/ keptDefer() { slice<nint> @out = default; GoFrame ᒐ = default; try {
// range over func on a coroutine: defer in body
foreach (var v in range<nint>(count(3).Invoke)) {
defer([GoFunc("keptDefer.func1")] () => {
@out = append(@out, v);
}, ref ᒐ);
}
} catch (Exception ᒐe) when (ᒐ.Is(ᒐe)) { ᒐ.Capture(); } finally { ᒐ.Run(); } return @out; }
defer in body. Go registers adeferin the loop body on the enclosing function, and runs it when that function returns. In theforeachform the body stays in the enclosing function, so thedeferregisters on that function’s frame like any other.body can park. With async twins, code that can block is compiled a second time asasynccode. A blocking body would need anasynclambda, and the iterator is a function value whoseasyncform is not known where the loop is converted.
What counts as a body that can block. A body blocks when it holds one of these, or calls a function of its
own package that does, through calls that name the function: a channel send; a channel receive; a select with
no default; a range over a channel; a call of time.Sleep, runtime.Gosched, (*sync.WaitGroup).Wait,
(*sync.Cond).Wait, (*testing.T).Run or (*testing.B).Run. A select with a default blocks only if one
of its case bodies does. The check does not follow a function literal (it runs only when called), a go
statement (its call runs on another goroutine), a call through a function value or an interface method, or a
function of another package that is not in the list. A body that waits only through one of those is converted, and
under M:N it holds its thread while it waits, where the foreach form would have parked: the program stays correct,
because the scheduler adds a thread, but that wait no longer gives its thread back. sync.Mutex.Lock is not in the
list: a lock wait alone does not make a function async under async twins either. In runtime, sync,
sync/atomic, internal/sync, time, iter and the internal/runtime/ packages, only the listed calls count.
The decision is made per package at conversion time, from the package’s own source and the fixed list, so
converting one package alone decides as converting it with its dependencies does, and one emission serves a
build with async twins and a build without. For a package that keeps a loop, the converter prints one line that
begins Range-over-func loops in <package>:. It gives the number of loops converted (direct) and the number
kept on a coroutine, and splits the kept loops into defer in body, body can park and other. other
counts the loops kept for a reason that gets no comment.
The emitted form of a kept loop (.Invoke, the spelled-out type arguments) is in
Generic Constraints. The loops kept for the other reasons listed under
the first rule get no comment.
Guarded by: RangeFuncLoweredCaptures (keptDefer, keptPark; output compared with Go), RangeFuncOracle
(its loops with a defer in the body), and the converter unit tests TestRangeOverFuncLoweringDecision
(one function per reason and per case that must not count),
TestRangeOverFuncCopiesAnAssignedYieldedVariable and TestRangeOverFuncBoxesItsYieldedVariablePerIteration.
← Implicit Pointer Dereferencing · Index · The go.golib support namespace →