给出一个struct看起来像
type foo struct {
i *int
}
Run Code Online (Sandbox Code Playgroud)
如果我想设置i为1,我必须
throwAway := 1
instance := foo { i: &throwAway }
Run Code Online (Sandbox Code Playgroud)
有没有办法在一行中完成这个,而不必给我的新i值它自己的名字(在这种情况下throwaway)?
正如邮件列表中所指出的,您可以这样做:
func intPtr(i int) *int {
return &i
}
Run Code Online (Sandbox Code Playgroud)
然后
instance := foo { i: intPtr(1) }
Run Code Online (Sandbox Code Playgroud)
如果你经常这样做的话.intPtr内联(见go build -gcflags '-m'输出),所以它应该没有性能损失.
不可以在一行中做到这一点.