英文:
Why i cant apply address operator (&) to functions return values directly
问题
我不明白为什么以下代码片段无法编译通过。编译器报告:
<!-- language: lang-none -->
无法获取 getAString() 的地址
代码如下:
func getAStringPointer() *string {
return &getAString()
}
func getAString() string {
return ""
}
但是,将函数的结果存储在辅助变量中,并返回该变量的地址,编译器就能正常工作。
func getAStringPointer() *string {
var aString = getAString()
return &aString
}
func getAString() string {
return ""
}
英文:
I don't get why the following code snippet isn't compiling. The compiler states:
<!-- language: lang-none -->
cannot take the address of getAString()
<p>
The code:
func getAStringPointer() *string {
return &getAString()
}
func getAString() string {
return ""
}
But, storing the results of the function in auxliary variable and return the address of that variable the compiler behaves OK.
func getAStringPointer() *string {
var aString = getAString()
return &aString
}
func getAString() string {
return ""
}
答案1
得分: 2
你不能将&
应用于那样的值(除非它是一个复合字面量)。根据规范:
对于类型为T的操作数x,地址操作
&x
生成一个类型为T的指针,指向x。操作数必须是可寻址的*,也就是说,要么是一个变量、指针间接引用或切片索引操作;或者是可寻址结构操作数的字段选择器;或者是可寻址数组的数组索引操作。作为对可寻址要求的例外,x也可以是一个(可能带括号的)复合字面量。如果对x的求值会导致运行时恐慌,那么对&x
的求值也会如此。
英文:
You can't apply &
to a value like that (unless it's a composite literal). From the spec:
> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论