pointers - 在go中找到常量的地址

标签 pointers go constants

我们编写了一个程序,通过它我们试图找到一个常量的地址。可以这样吗?

package main

func main() {
        const k = 5
        address := &k
}

它给出了一个错误,谁能告诉我们如何找到一个常量的地址?

最佳答案

简而言之:你不能

错误信息说:

cannot take the address of k

地址运算符&的操作数有限制。 Spec: Address operators:

For an operand x of type T, the address operation &x generates a pointer of type *T to x. 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 of x would cause a run-time panic, then the evaluation of &x does too.

常量列为可寻址,规范中未列为可寻址的事物(上面引用)不能 是地址运算符 & 的操作数(不能取它们的地址)。

不允许取常量的地址。这有两个原因:

  1. 常量可能根本没有地址。
  2. 即使在运行时将常量值存储在内存中,这也是为了帮助运行时保持常量: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/

相关文章:

c++ - 如何在 C++ 中的 const 覆盖函数中调用非 const 函数

c - 在链表中前进指针

http - DNS 查询是什么样的?

python - 无法跨 Python 验证 RSASSA-PSS 签名 -> Go

concurrency - goroutine 是如何工作的?

objective-c - 重复符号错误——全局常量

c++ - 从右值参数推导出对 const 的引用

c - 根据这段 C 代码,指针和变量的值是多少?

c - 返回结构数组或结构指针数组?

c++ - 指针还是数组?