复制带有嵌入指针的结构体

huangapple go评论67阅读模式
英文:

Copy struct with a embed pointer

问题

以下是代码的翻译:

type A struct{
    v int
}

type B struct{
    *A
}

b := B{new(A)}
c := b
b.v = 2
println(c.v) // 输出2而不是0

在上面的代码中,我不太理解发生了什么,我猜测是因为 v 属于指针类型的 .A,所以复制操作并没有复制该值,但我不确定。另外,有没有办法解决这个问题?我不能将嵌入字段的类型改为值类型,因为我需要指针接收者的方法。

英文:
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.

答案1

得分: 1

在你提供的代码中,A 是一个具有成员变量 v 的结构体,其类型为 int,而 B 是一个具有成员变量 A 的结构体,其类型为 *A。因此,当你执行 c:=b 这个赋值操作时,c 变成了 B 结构体的一个实例,而 c.Ab.A 的一个副本,它是一个指针,所以它们都指向同一个位置。

你说你需要在指针接收器上定义方法。这并不意味着你需要 *A,它只意味着你需要 A 是可寻址的,这样当你调用方法时可以取得它的地址。也就是说:

type B struct {
  A
}

其中

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

你仍然可以这样做:

b:=B{}
b.f()

因为在这个上下文中,可以取得 b 的地址。

英文:

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.

huangapple
  • 本文由 发表于 2022年10月29日 13:20:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/74242996.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定