[英]Golang - conversion between structs
我有两个结构
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}
}
类型A
和B
具有不同的基础类型,因此它们不能相互转换。 没门。
因此,要么手动复制,要么提供转换器功能或执行此复制的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.