Golang - 结构之间的转换

时间:2016-06-09 11:31:04

标签: data-structures go casting

我有两个结构

type A struct {
    a int
    b string
}

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

我希望将A类型的变量转换为B类(A只定义了对某些部分至关重要的基本字段,B另一方面包含了完整的数据)。 / p>

是否可以在Go中,或者我是否必须手动复制字段(或创建方法A.GetB()或类似的东西并使用此方法将A转换为B)?

2 个答案:

答案 0 :(得分:6)

通过转换你的意思是:

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

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

答案 1 :(得分:-2)

类型AB具有不同的基础类型,因此无法将它们相互转换。没办法。

因此要么手动复制,要么提供转换器功能或执行此复制的方法。