I have a lot of constraints in the issue I am encountering, so I have greatly simplified it to this unnatural code containing the following stuff:
- A struct named
Rect
rA
andrB
both of which point to a newRect
objectr1
andr2
, which areinterfaces
containingrA
andrB
r1Adr
andr2Adr
, which areinterfaces
containing the addresses ofrA
andrB
I want to do rA = rB
without being allowed to reference rA
or rB
after declaring my variables.
(Note: you would think it would be easy, and that you would just do *r1.(*Rect) = *r2.(*Rect)
. However, the issue with this approach is that it does not point rA
to rB
's Rect object—it merely clones the values of rB
's Rect to rA
's Rect. So, I instead have to dereference a pointer to rA
(r1Adr
) and assign it to rB
so that rA
points to the same Rect object as rB
.)
Below is my attempt at doing so:
type Rect struct {
width int
}
func main() {
rA := new(Rect)
rB := new(Rect)
var r1, r2, r1Adr, r2Adr any
r1 = rA
r2 = rB
r1Adr = &rA
r2Adr = &rB
*r1Adr.(**Rect) = *r2Adr.(**Rect)
// print the address of each Rect object being stored
fmt.Printf("%p, %p, %p, %p, %p, %p", rA, rB, r1, r2, *r1Adr.(**Rect), *r2Adr.(**Rect))
}
0xc00001c038, 0xc00001c038, 0xc00001c030, 0xc00001c038, 0xc00001c038, 0xc00001c038
PLAYGROUND: https://go.dev/play/p/VnQwx6V7DNa
As you can see from the output, rA
is correctly updating to rB
, and r1Adr
and r2Adr
are reflecting this perfectly. However, r1
's rA
is not updating to rB
, which we know because its output is different. Why is this? If rA
is being updated to rB
, and if r1
stores rA
, then how is it that the rA
pointed to by r1
is not updating to rB
?
Any insight as to how I can initialize r1
in such a way (without changing it from an interface) that it properly updates after doing *r1Adr.(**Rect) = *r2Adr.(**Rect)
would be greatly appreciated.
CodePudding user response:
rA
and rB
are two pointers pointing to separate objects, A
and B
.
r1
is an interface pointing to A
, and r2
is an interface pointing to B
.
r1Addr
is an interface pointing to &rA, and
r2Addris an interface pointing to
&rB`.
Thus, when you update the contents of r1Addr1
, you make rA
point to rB
.
However, r1
and r2
are still pointing to A
and B
. They did not change.