英文:
How to reference pointers to the same struct object from outside the scope in which they were defined
问题
在下面的代码中,两个指针变量 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) // 打印每个变量指向的 Rect 的地址
}
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) // 打印每个变量指向的 Rect 的地址
}
0xc00001c030, 0xc00001c038
(错误的输出)
PLAYGROUND: https://go.dev/play/p/ld0C5Bkmxo3
英文:
In the below code, two pointer variables, r1
and r2
(of type *Rect
), reference the same struct object (of type 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
(GOOD OUTPUT)
How would you reference r1
and r2
to the same struct object from outside of the function in which they were defined? In other words, how would you create a function to replace r1 = r2
? My attempt at dereferencing and then assigning the variables from within an external function did not succeed at referencing r1
to r2
's referenced struct object:
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
(BAD OUTPUT)
PLAYGROUND: https://go.dev/play/p/ld0C5Bkmxo3
答案1
得分: 1
如果你需要在函数内部改变指针所指向的位置,你需要传递它的地址:
func assign(r1, r2 **Rect) {
*r1 = *r2
}
func main() {
r1 := new(Rect)
r2 := new(Rect)
assign(&r1, &r2)
fmt.Printf("%p, %p", r1, r2) // 打印每个变量所指向的 Rect 的地址
}
PLAYGROUND: https://go.dev/play/p/5fAakjB50JJ
英文:
If you need to change where a pointer points to within a function, you have to pass the address of it:
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
}
PLAYGROUND: https://go.dev/play/p/5fAakjB50JJ
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论