Appearance
Go: xs[i] = e on an owned slice
Status: accepted · Date: 2026-12-01
Step 4 of the Go plan lists xs[i] = e among the slice operations left to do. This record says when the proved path accepts it.
The decision
xs[i] = e, for a local slicexs, becomeslet xs := Go.sliceSet xs i e.Go.sliceSetisList.setat a non-negative index. Go evaluates the operands of the index and the right side first, in the usual order, and only then tests the index and stores the value (Go specification, "Assignment statements"). The output does the same. It checks the divisors and indexes ofiand then ofe, then tests the index withGo.sliceFault, then sets the element. So a division by zero inepanics before an index out of range does.- The interpreter has the same rule (
Eval.setIndex), andProof.setIndex_soundshows that the code agrees with it. - The list model is exact only when no other slice shares the array of
xs. Soxs[i] = ecounts as a use that needs ownership, likexs = append(xs, …)(Owned.check, see the append decision record).xsmust not be a parameter. Nothing may read it exceptlen(xs),xs[j]andreturn xs. It may be given only a new slice.
Counted loops over len(xs)
for i := 0; i < len(xs); i++ { xs[i] = … } is accepted. Go evaluates i < len(xs) before each iteration, and the interpreter evaluates the bound once, before the loop. The two agree because the body cannot change what the bound reads, and this is proved, not assumed:
Eval.boundReadsgiveslen(xs)the readslenandEval.lenKey xs, notxs.Eval.countedBodySaferefuses a body that assigns, declares or shadowsxs, but allowsxs[j] = e.Proof.Bound.stmt_okshows that a body that the check accepts keeps the value of each name the bound reads, and keeps the length of each slice whoselenit reads.xs[j] = ekeeps the length becauseEval.setIndexgives a list of the same length (Proof.Bound.setIndex_slice).Proof.Bound.bound_relshows that the bound then has the same value, up to the contents of a slice that onlylenreads, andProof.Bound.counted_bound_fixedconcludes that an integer bound has the same value after each iteration as before it.- This needs
lento be the predeclared function. A package may declare its ownlen, so the interpreter and the translator refuse such a bound (Eval.lenBuiltin).
The range loop over xs stays refused. It walks the elements, not just the length, so a set element would change what later iterations see.
Refused
xs[i] = eon a parameter, whose array the caller sees, or on a slice that another slice, call or struct may share.xs[i] = ein arangeloop overxs, and in a counted loop whose bound readsxsother than throughlen(xs), as ini < xs[0]. Both loops fix the names that their bound or slice reads (Eval.countedBodySafe).- A counted bound that calls
lenwhen the package declares the namelen(Eval.lenBuiltin). xs[i] op= e,xs[i]++,xs[i].f = e,xs[i][j] = e, and a statement with several targets.
This page is docs/decisions/2026-12-01-go-slice-assign.md at commit 5f1d031.
