如何在 Go 中存储对操作结果的引用? [英] How can I store reference to the result of an operation in Go?

查看:26
本文介绍了如何在 Go 中存储对操作结果的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,很难用语言来描述它,但假设我有一个存储 int 指针的映射,并且想要将操作的结果作为另一个键存储在我的哈希中:

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"])

这不起作用并给我错误:cannot take the address of *m["x"] &*m["y"]

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

想法?

推荐答案

指针是内存地址.例如一个变量在内存中有一个地址.

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

3 + 4 这样的操作的结果没有地址,因为没有为其分配特定的内存.结果可能只存在于处理器寄存器中.

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.

看这个例子:

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"])

输出(在 Go Playground 上试试):

Output (try it on the Go Playground):

0x10438300 3

注意:如果上面的代码在一个函数中,我们刚刚放入映射中的局部变量(d)的地址将继续存在,即使我们从函数返回(也就是说,如果 map 在外部返回或创建 - 例如一个全局变量).在 Go 中,获取并返回局部变量的地址是完全安全的.编译器将分析代码,如果地址(指针)转义函数,它将自动在堆上(而不是在堆栈上)分配.有关详细信息,请参阅常见问题解答:如何知道变量是在堆上还是在堆栈上分配?

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?

注意 #2: 还有其他方法可以创建指向值的指针(如本答案所述:我如何在 Go 中执行文字 *int64 ?),但它们只是技巧",并没有更好或更有效.使用局部变量是最干净和推荐的方式.

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]

输出是一样的.在 Go Playground 上试试.

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

这篇关于如何在 Go 中存储对操作结果的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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