简体   繁体   English

Golang - 结构之间的转换

[英]Golang - conversion between structs

I have two structs 我有两个结构

type A struct {
    a int
    b string
}

type B struct {
    A
    c string
    // more fields
}

I'd like to convert variable of type A to type B (A has defined only basic fields that are crucial for some parts, B on the other hand contains 'full' data). 我想将类型A的变量转换为类型B(A仅定义了对某些部分至关重要的基本字段,而B另一方面包含“完整”数据)。

Is it possible in Go, or do I have to copy fields manually (or create a method A.GetB() or something like this and use this to convert A to B)? 是否可以在Go中,或者我是否必须手动复制字段(或创建方法A.GetB()或类似的东西并使用它将A转换为B)?

By converting do you mean this: 转换你的意思是:

func main() {
    // create structA of type A
    structA := A{a: 42, b: "foo"}

    // convert to type B
    structB := B{A: structA}
}

The types A and B have different underlying types so they cannot be converted into each other. 类型AB具有不同的基础类型,因此它们不能相互转换。 No way. 没门。

So either copy manually or provide converter functions or methods which do this copying. 因此,要么手动复制,要么提供转换器功能或执行此复制的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM