在下面的代码中,两个指针变量r1和r2(类型*Rect)引用相同的结构对象(类型Rect):
type Rect struct {
width int
}
func main() {
r1 := new(Rect)
r2 := new(Rect)
r1 = r2
fmt.Printf("%p, %p", r1, r2) // prints the addresses of the Rects being pointed to by each variable
}
0xc00001c038, 0xc00001c038 (良好的输出)
您将如何从定义它们的函数外部引用r1和r2引用相同的结构对象?换句话说,您将如何创建一个函数来替换r1 = r2?我在外部函数中取消引用然后分配变量的尝试未能成功引用r1到r2的引用结构对象:
func assign(r1, r2 *Rect) {
*r1 = *r2
}
func main() {
r1 := new(Rect)
r2 := new(Rect)
assign(r1, r2)
fmt.Printf("%p, %p", r1, r2) // prints the addresses of the Rects being pointed to by each variable
}
0xc00001c030, 0xc00001c038 (错误输出)
游乐场: https://go.dev/play/p/ld0C5Bkmxo3
白衣非少年
相关分类