Golang切片参考混乱 [英] Golang slice reference confusion

查看:79
本文介绍了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]]

when appending slice,val is expected to be [[0, 1], [1, 2]], but got [[1,2], [1,2]]

推荐答案

之所以会发生这种情况,是因为切片val包含指向其子切片的指针,而不是子切片本身的指针.在代码中,您最初将指向values的指针放置在位置val[0].然后,修改values,然后在val[1]中将指针设置为values.但是val[0]val[1]都指向相同的基础对象(values),该对象已被修改.

This happens because the slice val contains pointers to its subslices, rather than the subslices themselves. In your code, you initially place a pointer to values in positions val[0]. Then you modify values and then set a pointer to values in val[1]. But both val[0] and val[1] point to the same underlying object (values), which has been modified.

您可以通过在外循环的每次迭代中创建一个新的values切片来解决此问题,这样,val的每个子切片将是一个不同的切片.

You can fix this by creating a new values slice on each iteration of the outer loop, this way each sub slice of val will be a different slice.

例如:

func main() {
    val := make([][]int, 2)
    for i:=0; i<2; i++ {
        values := make([]int, 0, 100)
        for j:=0; j<2; j++ {
            values = append(values, i+j)
        }
        val[i] = values
        fmt.Println(values, val) //
    }
    fmt.Println(val)
}

fmt.Println的输出:

[0 1] [[0 1] []]    // values, val
[1 2] [[0 1] [1 2]] // values, val
[[0 1] [1 2]]       // val

这篇关于Golang切片参考混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆