Go语言中的‘cannot take address of XXX‘

本文介绍了Go语言中'cannot take address of XXX'错误的原因,包括常量、map索引表达式和函数返回值不可寻址。常量和函数返回值因未分配特定内存而无法获取地址,而map值的地址可能导致指向无效地址。同时,复合文字可以通过&运算符获取其地址。
摘要由CSDN通过智能技术生成

先上个结论:常量、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将被重新分配。如果可以检索映射元素的地址,那么这样的指针可能会在重新分配之后指向无效地址。因此,不允许获取映射值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值