Golang 切片引用混淆

package main


import (

    "fmt"

)


func main() {

    values := make([]int, 0, 100)

    val := make([][]int, 2)

    for i:=0; i<2; i++ {

        values = values[:0]

        for j:=0; j<2; j++ {

            values = append(values, i+j)

        }

        val[i] = values

        fmt.Println(values, val) //

    }

    fmt.Println(val)

}

https://play.golang.org/p/5x60VfDXbFw


附加切片时,val 应该是 [[0, 1], [1, 2]],但得到的是 [[1,2], [1,2]]


月关宝盒
浏览 110回答 2
2回答

慕尼黑5688855

发生这种情况是因为切片val包含指向其子切片的指针,而不是子切片本身。在您的代码中,您最初放置了一个指向valuesin positions的指针val[0]。然后你修改values然后设置一个指向valuesin 的指针val[1]。但是val[0]和都val[1]指向相同的基础对象 ( values),该对象已被修改。您可以通过在外循环的每次迭代中创建一个新values切片来解决此问题,这样每个子切片都val将是不同的切片。例如:func main() {&nbsp; &nbsp; val := make([][]int, 2)&nbsp; &nbsp; for i:=0; i<2; i++ {&nbsp; &nbsp; &nbsp; &nbsp; values := make([]int, 0, 100)&nbsp; &nbsp; &nbsp; &nbsp; for j:=0; j<2; j++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; values = append(values, i+j)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; val[i] = values&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(values, val) //&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(val)}输出自fmt.Println:[0 1] [[0 1] []]&nbsp; &nbsp; // values, val[1 2] [[0 1] [1 2]] // values, val[[0 1] [1 2]]&nbsp; &nbsp; &nbsp; &nbsp;// val

狐的传说

您应该在 for 循环中初始化值,values = []int{}代码如下:package mainimport (&nbsp; &nbsp; "fmt")func main() {&nbsp; &nbsp; var (&nbsp; &nbsp; &nbsp; &nbsp; valLength = 2&nbsp; &nbsp; )&nbsp; &nbsp; val := make([][]int, valLength)&nbsp; &nbsp; for i := 0; i < valLength; i++ {&nbsp; &nbsp; &nbsp; &nbsp; values := []int{}&nbsp; &nbsp; &nbsp; &nbsp; for j := 0; j < 2; j++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; values = append(values, i+j)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; val[i] = values&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(values, val) //&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(val)}而且您只需更改变量valLength即可获得所需的任何长度的切片。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go