在下面的代码中,两个指针变量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
1 回答
白衣非少年
TA贡献1155条经验 获得超0个赞
如果您需要更改指针在函数中指向的位置,则必须传递它的地址:
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
}
游乐场: https://go.dev/play/p/5fAakjB50JJ
- 1 回答
- 0 关注
- 81 浏览
添加回答
举报
0/150
提交
取消