为什么可以通过分配但不能在for循环中更改切片的功能?

问题描述 投票:0回答:1

我需要在接收切片指针的函数中将每个分数更改为其他一些值,我可以通过赋值来更改这些值,但是如果我在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}]]
loops pointers go slice
1个回答
0
投票

因为range给您两个元素:

  • 索引
  • a copy元素,如果您迭代切片。
© www.soinside.com 2019 - 2024. All rights reserved.