Range Over Structs Copies Each Element
Range variables are copies of each element, so field writes silently vanish; fix it with index writes or a slice of pointers.
Code
package main
import "fmt"
type Task struct {
Name string
Done bool
}
func main() {
tasks := []Task{{Name: "lint"}, {Name: "test"}, {Name: "build"}}
// Range over structs copies each element:t 是副本,写字段不会写回切片
for _, t := range tasks {
t.Done = true
}
fmt.Println("after copy loop:", tasks[0].Done, tasks[1].Done, tasks[2].Done)
// 修法一:按索引直写元素本体
for i := range tasks {
tasks[i].Done = true
}
fmt.Println("after index write:", tasks[0].Done, tasks[1].Done, tasks[2].Done)
// 修法二:元素存指针,副本里的指针指向同一份数据
pointers := []*Task{{Name: "a"}, {Name: "b"}}
for _, t := range pointers {
t.Done = true
}
fmt.Println("pointer elements:", pointers[0].Done, pointers[1].Done)
}What the code does
The load-bearing piece is the function main — everything else is wiring.
Repetition is confined to for _, t := range tasks — the rest of the file is straight-line.
Applying it
Output lines are prefixed (after copy loop:, after index write:, pointer elements:), which keeps the mapping between steps and output visible.
The structure at work
for _, t := range pointers {
t.Done = true
}
for _, t := range tasks {
t.Done = true
}
for i := range tasks {
tasks[i].Done = true
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SemVer Range CheckerCheck whether a semantic version satisfies an npm-style range such as caret, tilde, comparison sets, wildcards, or hyphen ranges.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Range Over Structs Copies Each Element print when run?
- No setup needed: run the file and look for labeled lines like `after copy loop:`, `after index write:`, `pointer elements:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.