dongle7637 2018-12-28 03:24
浏览 17
已采纳

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

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

  • 写回答

3条回答 默认 最新

  • dtjw6660 2018-12-28 03:39
    关注

    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.

    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.

    For example:

    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)
    }
    

    Output from fmt.Println:

    [0 1] [[0 1] []]    // values, val
    [1 2] [[0 1] [1 2]] // values, val
    [[0 1] [1 2]]       // val
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分