我有两个结构
type A struct {
a int
b string
}
type B struct {
A
c string
// more fields
}
我想将类型 A 的变量转换为类型 B(A 只定义了对某些部分至关重要的基本字段,另一方面 B 包含“完整”数据)。
在 Go 中是否可行,还是我必须手动复制字段(或创建一个方法 A.GetB() 或类似的方法并使用它来将 A 转换为 B)?
最佳答案
转换是指:
func main() {
// create structA of type A
structA := A{a: 42, b: "foo"}
// convert to type B
structB := B{A: structA}
}
关于data-structures - Golang - 结构之间的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37724757/