指向非复合字面量的指针

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

Pointer to non-composite literal

问题

有没有一种常用的方法来获取非复合字面量的指针?

x := 5
y := &x

上述代码可以工作,但是非常冗长。

英文:

Is there an established pattern for getting pointers to non-composite literals?

x := 5
y := &x

The above code works, but is awfully verbose.

答案1

得分: 9

如果我理解正确,x 的唯一目的是分配 int,我建议更加“冗长”一些的写法:

y := new(int)
*y = 5

我认为你已经找到了最短的写法。由于 & 运算符要求其操作数要么是可寻址的,要么是复合字面量,你要么继续使用你的写法来获取可寻址的内容,要么可以采用我的建议,完全避免使用 &

英文:

If I understand correctly that the only point of x is to allocate the int, I recommend something even more "verbose":

y := new(int)
*y = 5

I don't see getting it any shorter than what you have. Since the & operator requires its operand to be either addressable or a composite literal, you're either stuck doing what you're doing to get something addressable, or you can do what I suggest and avoid the & altogether.

huangapple
  • 本文由 发表于 2013年7月12日 04:53:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/17603301.html
匿名

发表评论

匿名网友

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

确定