先上个结论:常量、map索引表达式和函数返回的值是不可寻址的。
来自某本书的摘抄-----
“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.”
实际上,像 4、int64(4) 这样的常量或像 foo() 这样的函数返回值没有地址,因为没有为它们分配特定的内存(局部变量在函数被调用结束后内存会被回收,而常量由于本身特性是不可以被改变的,因此不能通过指针来进行修改);它们可以(maybe)在处理器寄存器中(基础类型可能在,但是复杂类型也许在栈中)。而对于map的元素num增加或减少的时候,则map将被重新分配。如果可以检索映射元素的地址,那么这样的指针可能会在重新分配之后指向无效地址。因此,不允许获取映射值的地址。
(可以将 & 视为获取某个现有变量的地址的运算符,但有一个例外:可以创建一个复合文字并使用 & 来获取其地址,例如 &T{}、&map[string ]int64{"a": 1} 或 &[]int{} 是有效的表达式。)

推荐阅读:3.2 计算机结构 · Go语言高级编程 (gitbooks.io)
推荐阅读: Solve 'cannot take address of XXX' error in Go (Golang) (gosamples.dev)
本文介绍了Go语言中'cannot take address of XXX'错误的原因,包括常量、map索引表达式和函数返回值不可寻址。常量和函数返回值因未分配特定内存而无法获取地址,而map值的地址可能导致指向无效地址。同时,复合文字可以通过&运算符获取其地址。
4731

被折叠的 条评论
为什么被折叠?



