我需要在接收切片指针的函数中将每个分数更改为其他一些值,我可以通过分配来更改值,但如果我在 for 循环中执行此操作,则不会发生任何变化。这是为什么?
package main
import (
"fmt"
"sync"
"time"
)
type TestType struct {
id int
score float64
}
func worker(index int, wg *sync.WaitGroup, listScores *[][]TestType) {
defer wg.Done()
time.Sleep(1000 * time.Millisecond)
// It works by assigning.
(*listScores)[index] = []TestType{{index + 1, 2.22},
{index + 1, 2.22},
{index + 1, 2.22},}
// It doesn't work in a for loop.
//for _, score := range (*listScores)[index] {
// score.score = 2.22
//}
}
func main() {
scoresList := [][]TestType{
{{1, 0.0},
{1, 0.0},
{1, 0.0},},
{{2, 0.0},
{2, 0.0},
{2, 0.0},
},}
fmt.Println(scoresList)
var wg sync.WaitGroup
for i, _ := range scoresList {
wg.Add(1)
go worker(i, &wg, &scoresList)
}
wg.Wait()
fmt.Println(scoresList)
}
通过为其分配一个新的整个切片,可以将分数更改为 2.22:
[[{1 0} {1 0} {1 0}] [{2 0} {2 0} {2 0}]]
[[{1 2.22} {1 2.22} {1 2.22}] [{2 2.22} {2 2.22} {2 2.22}]]
但是,如果我像注释中那样在 for 循环中执行此操作,则输出是这样的:
[[{1 0} {1 0} {1 0}] [{2 0} {2 0} {2 0}]]
[[{1 0} {1 0} {1 0}] [{2 0} {2 0} {2 0}]]
鸿蒙传说
相关分类