Go 中的类型转换结构是空操作吗?

Voj*_*ane -1 casting go

考虑 Go 中的以下代码

type A struct {
  f int
}

type B struct {
  f int `somepkg:"somevalue"`
}


func f() {
  var b *B = (*B)(&A{1}) // <-- THIS

  fmt.Printf("%#v\n", b)
}
Run Code Online (Sandbox Code Playgroud)

标记的行会导致内存副本(我想避免,因为 A 附加了许多字段)还是只是重新解释,类似于将 an 转换int为 an uint

编辑:我担心是否必须复制整个结构,类似于将字节切片转换为字符串。因此,指针副本对我来说是无操作

Bur*_*dar 5

它被称为转换。该表达式(&A{})创建一个指向 type 实例的指针A(*B)并将该指针转换为 a *B。在那里复制的是指针,而不是结构。您可以使用以下代码验证这一点:

 a:=A{}
 var b *B = (*B)(&a)
 b.f=2
 fmt.Printf("%#v\n", a)
Run Code Online (Sandbox Code Playgroud)

打印 2。