Terminology (3)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Iteration variable
- A variable receiving an index, key or value for a loop iteration.
- Element copy
- A separate value obtained from an original collection element.
- Original-element identity
- Referring to the collection’s stored element so that writes through either reference affect the same object.
Loop shape, binding and element identity
Go uses for for counted loops, condition-controlled loops and range iteration. The range operand determines what is supplied: traversing a slice can provide an index and an element value. The variable receiving that value and the original stored element are separate objects.
When code retains pointers from a traversal, ask two questions: do the pointers name distinct variables, and do they name the original elements? The declaration or assignment in the range clause matters to the first question. The address expression matters to the second. This reading uses the Go 1.22+ loop-variable rules already stated in its probes.
01One keyword covers several loop shapes
One keyword covers several loop shapes
An inventory-admin editor applies a bulk count correction to selected records, then hands those records to a detail panel. The panel must reach the original entries. A distinct, valid pointer can still name a range copy instead.
Before changing the inventory traversal, use a reduced control-flow probe with no records. Predict the counted total, then locate initialization, the repeated condition and advancement. Its numbers are loop-control values, not stock counts.
package main
import "fmt"
func main() {
total := 0
for index := 1; index <= 3; index++ {
total += index
}
fmt.Println("total", total)
}
go run main.go
Save one complete example at a time under the shown filename in a fresh folder. Run the shown command. The browser lab supplies its editor, input fixtures and runner.
02A struct iteration value is a copy
A struct iteration value is a copy
With the loop shape checked, return to the inventory records. The editor needs to write a supplied correction into storage. This reduced probe omits selection and tries to add three units to both records; predict the original slice after this actual loop.
package main
import "fmt"
func main() {
type Item struct {
Count int
}
items := []Item{{Count: 2}, {Count: 4}}
for _, item := range items {
item.Count += 3
}
fmt.Println("original", items[0].Count, items[1].Count)
}
03Distinct iteration variables can still be detached copies
Distinct iteration variables can still be detached copies
The detail panel must retain handles after traversal finishes. Reduce that identity question to an integer slice: this Go 1.22+ probe compares assignment to an existing range variable with declaration in the clause, then changes the original slice. Predict the three reports.
package main
import "fmt"
func main() {
values := []int{2, 8}
var value int
reused := []*int{}
for _, value = range values {
reused = append(reused, &value)
}
copies := []*int{}
for _, value := range values {
copies = append(copies, &value)
}
values[0] += 10
fmt.Println("reused", *reused[0], *reused[1])
fmt.Println("copies", *copies[0], *copies[1])
fmt.Println("source", values[0], values[1])
}
04Map range gives no ordering promise
Map range gives no ordering promise
The inventory summary may arrive as counts labelled by location. Before using map visitation to order a display, check what it guarantees. Predict only the total, not a sequence of key visits. This program does not change the map during iteration.
package main
import "fmt"
func main() {
counts := map[string]int{"north": 2, "south": 4}
total := 0
for _, count := range counts {
total += count
}
fmt.Println("total", total)
}
05Practice
Repair the inventory correction editor
Input is item count, bonus, then count/selected pairs, where selected is 0 or 1. Item, decoding, reporting and the pointer-consuming caller are supplied.
The final selector returns selected original items in input order. After selection the caller adds 10 to the first original item if present, then adds 1 through each returned pointer. It prints original and selected counts; the source items slice is not resized while these handles are used.
Start the lab
Sum values, update selected original records, then return handles that preserve original identity.
Sources
Sign in to keep your read marks on every device. Sign in
Was this helpful?