douchao5864 2016-04-28 13:24 采纳率: 100%
浏览 65
已采纳

在golang范围复制之后,所有项目都指向src切片的最后一个项目

After I copy all items from a slice (src) into a new slice (dst) all items in dst point to the last item of src.

package main

import (
    "fmt"
)

func main() {
    src := []string{"a", "b", "c"}
    dst := []*string{}
    for _, val := range src {
        dst = append(dst, &val)
    }

    for i, s := range dst {
        fmt.Printf("%v - %v
", i, *s)
    }
}

>>> 0 - c
>>> 1 - c
>>> 2 - c

Why aren't "a" and "b" copied into the dst slice?

  • 写回答

2条回答 默认 最新

  • dongtuan5367 2016-04-28 13:24
    关注

    The solution is simple, but counter intuitive in terms of what you would expect of the range statement.

    The variable val is instantiated only once and holds the value of src[i] in every iteration. It does not has the actual pointer to src[i]. Instead the value of src[i] is copied to the memory that is assigned to val. By taking the pointer of val you get exactly that, and not the pointer to src[i].

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        src := []string{"a", "b", "c"}
        dst := []*string{}
        for _, val := range src {
            dst = append(dst, &val)
        }
    
        for i, s := range dst {
            fmt.Printf("%v - %v - %p
    ", i, *s, s)
        }
    
        //modify only contents of first index
        *dst[0] = "hi val"
    
        for i, s := range dst {
            fmt.Printf("%v - %v - %p
    ", i, *s, s)
        }
    }
    
    >>>>
    0 - c - 0x1040a120
    1 - c - 0x1040a120
    2 - c - 0x1040a120
    0 - hi val - 0x1040a120
    1 - hi val - 0x1040a120
    2 - hi val - 0x1040a120
    

    While in hindsight this is obvious - for _, val -> := <- range src - it can can bite you in the ass if you are unaware of it, so therefore this warning.

    PS. this also applies to src as a map.

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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化