Golang - 结构之间的转换

Art*_*icz 4 casting go data-structures

我有两个结构

type A struct {
    a int
    b string
}

type B struct {
    A
    c string
    // more fields
}
Run Code Online (Sandbox Code Playgroud)

我想将类型A的变量转换为类型B(A仅定义了对某些部分至关重要的基本字段,而B另一方面包含"完整"数据).

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

jus*_*ius 6

转换你的意思是:

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

    // convert to type B
    structB := B{A: structA}
}
Run Code Online (Sandbox Code Playgroud)