1 回答
TA贡献1865条经验 获得超7个赞
因为range
给你两个元素:
索引
如果迭代切片,则为元素的副本。
不使用线程可以将代码更改为以下代码:
package main
import (
"fmt"
)
type testType struct {
id int
score float64
}
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)
for i := range scoresList {
scoresList[i] = []testType{{i + 1, 2.22},
{i + 1, 2.22},
{i + 1, 2.22}}
}
fmt.Println(scoresList)
}
如果要使用线程,则可以使用以下线程:
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)
for i := range (*listScores)[index] {
(*listScores)[index][i].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)
}
- 1 回答
- 0 关注
- 106 浏览
添加回答
举报