问题描述
我只是想知道为什么?有没有办法做到这一点,除了首先做一个变量赋值并且接受变量的指针?
package main
导入时间
func main(){
_ =& time.Now()
}
可能不令人满意的答案是你无法做到这一点,因为规范说明了这一点。该规范说,要使用&
,它必须是或复合文字,并且为了可寻址它必须是变量,指针间接或片段索引操作;或可寻址结构操作数的字段选择器;或可寻址的数组索引操作阵。函数调用和方法调用绝对不在列表中。
实际上,这可能是因为函数的返回值可能不是 a a可用地址;它可能在一个寄存器中(在这种情况下,它绝对不可寻址)或堆栈上(在这种情况下,它有一个地址,但是如果它被放入一个指向当前范围的指针中,则该地址无效)。可行性,Go必须做几乎完全相同的分配给一个变量,但Go是一种语言,它指出,如果它要为一个变量分配存储空间,那将是因为你说过,而不是因为编译器神奇地决定,所以它不会使函数的结果可寻址。
或者我可能会过度思考它,而他们根本就不想拥有一个返回一个值的函数与返回多个函数的函数的特殊情况:)
I just need a pointer to time.Time, so the code below seems invalid:
I just wonder why? Is there any way to do that except to do assignment to a variable first and take the pointer of the variable?
package main
import "time"
func main() {
_ = &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 :)
这篇关于如何从函数调用中获取返回值的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!