为什么我不能直接对函数的返回值应用地址运算符(&)?

huangapple go评论72阅读模式
英文:

Why i cant apply address operator (&) to functions return values directly

问题

我不明白为什么以下代码片段无法编译通过。编译器报告:

<!-- language: lang-none -->

无法获取 getAString() 的地址

代码如下:

func getAStringPointer() *string {
	return &amp;getAString()
}

func getAString() string {
	return &quot;&quot;
}

但是,将函数的结果存储在辅助变量中,并返回该变量的地址,编译器就能正常工作。

func getAStringPointer() *string {
	var aString = getAString()
	return &amp;aString
}

func getAString() string {
	return &quot;&quot;
}
英文:

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 &amp;getAString()
}

func getAString() string {
	return &quot;&quot;
}

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 &amp;aString
}

func getAString() string {
	return &quot;&quot;
}

答案1

得分: 2

你不能将&应用于那样的值(除非它是一个复合字面量)。根据规范:

对于类型为T的操作数x,地址操作&x生成一个类型为T的指针,指向x。操作数必须是可寻址的*,也就是说,要么是一个变量、指针间接引用或切片索引操作;或者是可寻址结构操作数的字段选择器;或者是可寻址数组的数组索引操作。作为对可寻址要求的例外,x也可以是一个(可能带括号的)复合字面量。如果对x的求值会导致运行时恐慌,那么对&x的求值也会如此。

英文:

You can't apply &amp; 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.

huangapple
  • 本文由 发表于 2017年4月7日 23:35:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/43282057.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定