doufen1933 2017-08-30 18:20
浏览 67
已采纳

在Go中复制循环变量的地址

In the following code sample, the result is not what I would expect:

package main

import "fmt"

func main() {
    src := map[int]int{1: 1, 2: 2, 3: 3}
    fmt.Println("src ", src)

    dst := make([]*int, 0, len(src))
    for k, _ := range src {
        dst = append(dst, &k)
    }
    for _, a := range dst {
        fmt.Print(*a, " ")
    }
    fmt.Println()
}

Result:

src map[1:1 2:2 3:3]
3 3 3

Go Playground: https://play.golang.org/p/BSDsd3nojz

but I understand what is happening. The unchanging address of k is being added to dst, so when I loop over dst, the same value is in every location: 3.

The address of k never changes in the loop, so the second loop keeps referring to that location, containing the last value it had, 3.

How can I get the address of the current value of k to be copied? Do I need something like this:

for k, _ := range src {
    key = new(int)
    *key = k
    dst = append(dst, key)
}

That seems awkward.

  • 写回答

1条回答 默认 最新

  • dongqichang7988 2017-08-30 18:28
    关注

    If you have a map[T]X and you want to get a []*T, you are on the right track with copying the loop variable and getting an address to it.

    There is a slightly slimmer way to do it than your way:

    for k := range src {
        key := k
        dst = append(dst, &key)
    }
    

    What you are adding to dst is not the address of the keys or values in the map, but rather the address of a copy of the key. That distinction may or may not matter to you.

    The reason that using the address of the loop variables doesn't work, is that the loop variables are single locations that get updated on each iteration. Value types like ints and structs are copyed each time you assign it to a new variable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办