[golang] cannot take the address of xxx()

package main

import "time"
func main() {
    _ = &time.Now()
}

编译的时候提示:cannot take the address of time.Now()

给出的解释
The probably unsatisfying answer is “you can’t do it because the spec says so.” The spec says that to use & on something it has to be addressable or a compound literal, and to be addressable it has to be “a variable, pointer indirection, or slice indexing operation; or a a field selector of an addressable struct operand; or an array indexing operation of an addressable array.” Function calls and method calls are definitely not on the list.

Practically speaking, it’s probably because the return value of a function may not have a usable address; it may be in a register (in which case it’s definitely not addressable) or on the stack (in which case it has an address, but one that won’t be valid if it’s put in a pointer that escapes the current scope. To guarantee addressability, Go would have to do pretty much the exact equivalent of assigning it to a variable. But Go is the kind of language that figures that if it’s going to allocate storage for a variable it’s going to be because you said to, not because the compiler magically decided to. So it doesn’t make the result of a function addressable.

Or I could be over-thinking it and they simply didn’t want to have a special case for functions that return one value versus functions that return multiple ?

详细的讨论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值