英文:
Easy way to assign int pointer values?
问题
给定一个类似的struct
结构:
type foo struct {
i *int
}
如果我想将i
设置为1,我必须这样做:
throwAway := 1
instance := foo { i: &throwAway }
有没有一种方法可以在一行内完成这个操作,而不必给新的i
值(在这种情况下是throwaway
)命名?
英文:
Given a struct
that looks like
type foo struct {
i *int
}
if I want to set i
to 1, I must
throwAway := 1
instance := foo { i: &throwAway }
Is there any way to do this in a single line without having to give my new i
value it's own name (in this case throwaway
)?
答案1
得分: 10
如在邮件列表中指出,你可以这样做:
func intPtr(i int) *int {
return &i
}
// 然后
instance := foo{i: intPtr(1)}
如果你需要经常这样做的话。intPtr
会被内联(参见go build -gcflags '-m'
的输出),所以几乎没有性能损失。
英文:
As pointed in the mailing list, you can just do this:
func intPtr(i int) *int {
return &i
}
and then
instance := foo { i: intPtr(1) }
if you have to do it often. intPtr
gets inlined (see go build -gcflags '-m'
output), so it should have next to no performance penalty.
答案2
得分: 5
这不可能在一行代码中完成。
英文:
No this is not possible to do in one line.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论