我有变量的结构类型和引用地址,但它不反映defer
函数中变量的最新值。
type XY struct {
S string
}
func CloseP(x *XY) {
if x != nil {
fmt.Println("Pointer-Closing", x.S)
}
}
func main() {
xp2 := &XY{"Pointer-X2 First"}
fmt.Println(xp2)
defer CloseP( xp2 )
xp2 = &XY{"Pointer-X2 Second"}
fmt.Println(xp2)
}
Output
&{Pointer-X2 First}
&{Pointer-X2 Second}
Pointer-Closing Pointer-X2 First
预期产出
0xc000086018
0xc000086018
Pointer-Closing Pointer-X2 Second
我的问题是:
- 为什么它在实际输出中显示为“&”,它假设打印变量的地址。
- 为什么延迟函数没有反映“xp2”变量的最新值?
所以对于第2 点- 我已经实现了以下功能。有人可以告诉我这是解决此问题的最佳方法。
func main() {
xp2 := XY{"Pointer-X2 First"}
defer CloseP( &xp2 )
xp2 = XY{"Pointer-X2 Second"}
}
输出是
Pointer-Closing Pointer-X2 Second