英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论