Golang - conversion between structs

早过忘川 提交于 2019-12-22 08:35:13

问题


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).

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)?


回答1:


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}
}



回答2:


The types A and B have different underlying types so they cannot be converted into each other. No way.

So either copy manually or provide converter functions or methods which do this copying.



来源:https://stackoverflow.com/questions/37724757/golang-conversion-between-structs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!