Geo*_*Geo 2 memory pointers go
当我看到以下代码时,我有点困惑:
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的原因吗?
我想出了这种代码的一个动机:避免"意外复制结构".
如果使用struct变量来保存新创建的结构:
bigBox := BigBox{}
Run Code Online (Sandbox Code Playgroud)
你可以像这样意外复制结构
myBox := bigBox // Where you just want a refence of bigBox.
myBox.BubbleGumsCount = 4
Run Code Online (Sandbox Code Playgroud)
或者像这样
changeBoxColorToRed(bigBox)
Run Code Online (Sandbox Code Playgroud)
这里changeBoxColorToRed
是
// It makes a copy of entire struct as parameter.
func changeBoxColorToRed(box bigBox){
// !!!! This function is buggy. It won't work as expected !!!
// Please see the fix at the end.
box.Color=red
}
Run Code Online (Sandbox Code Playgroud)
但是如果你使用结构指针:
bigBox := &BigBox{}
Run Code Online (Sandbox Code Playgroud)
没有复制
myBox := bigBox
Run Code Online (Sandbox Code Playgroud)
和
changeBoxColorToRed(bigBox)
Run Code Online (Sandbox Code Playgroud)
将无法编译,让您有机会重新考虑设计changeBoxColorToRed
.修复很明显:
func changeBoxColorToRed(box *bigBox){
box.Color=red
}
Run Code Online (Sandbox Code Playgroud)
新版本changeBoxColorToRed
不会复制整个结构并正常工作.