0
type A struct{
v int
}

type B struct{
*A
}

b:=B{new(A)}
c:=b
b.v=2
println(c.v)//2 not 0

My problem is illustrated in the above code. I don't quite understand what is happening here, I assume it's that the v belongs to .A which is a pointer, so copying doesn't copy the value, but I'm not sure. Also, is there a way to solve this problem? I can't change the embed to value because i need the methods on pointer receivers.

G.M
  • 33
  • 3

1 Answers1

1

In the code you included, A is a struct with a member variable v whose type is int, and B is a struct with member variable A whose type is *A. Thus, when you assign c:=b, c becomes an instance of struct B, and c.A is a copy of b.A, which is a pointer, so they both point to the same location.

You said you need methods on pointer receivers. That doesn't mean you need *A, it only means you need A to be addressable, so when you call the methods its address can be taken. That is:

type B struct {
  A
}

where

func (a *A) f() {...}

you can still do:

b:=B{}
b.f()

because at this context, the address of b can be taken.

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • I need pointer receiver because some methods of A may change v. – G.M Oct 29 '22 at 16:19
  • You don't need a pointer struct member to use a pointer receiver. In the example I gave, `b.f()` has a pointer receiver, without declaring `b.A` as a pointer. What matters is that when you call a method, the receiver is addressable. – Burak Serdar Oct 29 '22 at 17:10
  • "I need pointer receiver because some methods of A may change v." yes, the answer acknowledges that. You ned a pointer receiver, but A does not have to be a pointer. – erik258 Oct 29 '22 at 17:14