我们编写了一个程序,通过它我们试图找到一个常量的地址。可以这样吗?
package main
func main() {
const k = 5
address := &k
}
它给出了一个错误,谁能告诉我们如何找到一个常量的地址?
最佳答案
简而言之:你不能。
错误信息说:
cannot take the address of k
地址运算符&
的操作数有限制。 Spec: Address operators:
For an operand
x
of typeT
, the address operation&x
generates a pointer of type*T
tox
. The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. As an exception to the addressability requirement,x
may also be a (possibly parenthesized) composite literal. If the evaluation ofx
would cause a run-time panic, then the evaluation of&x
does too.
常量不列为可寻址,规范中未列为可寻址的事物(上面引用)不能 是地址运算符 &
的操作数(不能取它们的地址)。
不允许取常量的地址。这有两个原因:
- 常量可能根本没有地址。
- 即使在运行时将常量值存储在内存中,这也是为了帮助运行时保持常量:constant。如果可以获取常量值的地址,则可以将地址(指针)分配给变量,然后可以更改它(指向的值,常量的值)。 Robert Griesemer(Go 的作者之一)写了为什么不允许使用字符串文字的地址:“如果你可以获取字符串常量的地址,你可以调用一个函数 [分配给指向的值导致]可能会产生奇怪的效果——你当然不希望文字字符串常量发生变化。”(source)
如果您需要一个指向等于该常量的值的指针,请将其分配给一个可寻址的变量,以便您可以获取其地址,例如
func main() {
const k = 5
v := k
address := &v // This is allowed
}
但是要知道,在 Go 中,数字常量表示任意精度的值并且不会溢出。当您将常量的值分配给变量时,它可能是不可能的(例如,常量可能大于您分配给它的变量类型的最大值 - 导致编译时错误),或者它可能不一样(例如,在浮点常量的情况下,它可能会丢失精度)。
关于pointers - 在go中找到常量的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35146286/