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.

GoData Integrity

Code

gosnippet
31 lines
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

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.