douhe1864 2015-12-10 08:46
浏览 36
已采纳

如何在Go中存储对操作结果的引用?

Okay it's hard to describe it in words but let's say I have a map that stores int pointers, and want to store the result of an operation as another key in my hash:

m := make(map[string]*int)

m["d"] = &(*m["x"] + *m["y"])

This doesn't work and gives me the error: cannot take the address of *m["x"] & *m["y"]

Thoughts?

  • 写回答

3条回答 默认 最新

  • dongshan1959 2015-12-10 08:52
    关注

    A pointer is a memory address. For example a variable has an address in memory.

    The result of an operation like 3 + 4 does not have an address because there is no specific memory allocated for it. The result may just live in processor registers.

    You have to allocate memory whose address you can put into the map. The easiest and most straightforward is to create a local variable for it.

    See this example:

    x, y := 1, 2
    m := map[string]*int{"x": &x, "y": &y}
    
    d := *m["x"] + *m["y"]
    m["d"] = &d
    
    fmt.Println(m["d"], *m["d"])
    

    Output (try it on the Go Playground):

    0x10438300 3
    

    Note: If the code above is in a function, the address of the local variable (d) that we just put into the map will continue to live even if we return from the function (that is if the map is returned or created outside - e.g. a global variable). In Go it is perfectly safe to take and return the address of a local variable. The compiler will analyze the code and if the address (pointer) escapes the function, it will automatically be allocated on the heap (and not on the stack). For details see FAQ: How do I know whether a variable is allocated on the heap or the stack?

    Note #2: There are other ways to create a pointer to a value (as detailed in this answer: How do I do a literal *int64 in Go?), but they are just "tricks" and are not nicer or more efficient. Using a local variable is the cleanest and recommended way.

    For example this also works without creating a local variable, but it's obviously not intuitive at all:

    m["d"] = &[]int{*m["x"] + *m["y"]}[0]
    

    Output is the same. Try it on the Go Playground.

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

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法