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
CodePudding user response:
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