当我看到以下代码时,我有点困惑:
bigBox := &BigBox{}
bigBox.BubbleGumsCount = 4 // correct...
bigBox.SmallBox.AnyMagicItem = true // also correct
Run Code Online (Sandbox Code Playgroud)
为什么或何时,我想做什么bigBox := &BigBox{}而不是bigBox := BigBox{}?它在某种程度上更有效吗?
代码示例取自此处.
样品2:
package main
import "fmt"
type Ints struct {
x int
y int
}
func build_struct() Ints {
return Ints{0,0}
}
func build_pstruct() *Ints {
return &Ints{0,0}
}
func main() {
fmt.Println(build_struct())
fmt.Println(build_pstruct())
}
Run Code Online (Sandbox Code Playgroud)
样品编号 3 :(为什么我会在这个例子中使用&BigBox,而不是直接使用BigBox作为结构?)
func main() {
bigBox := &BigBox{}
bigBox.BubbleGumsCount = 4
fmt.Println(bigBox.BubbleGumsCount)
}
Run Code Online (Sandbox Code Playgroud)
是否有理由调用build_pstruct而不是build_struct变体?这不是我们拥有GC的原因吗?