Golang - 结构之间的转换 [英] Golang - conversion between structs
本文介绍了Golang - 结构之间的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个结构体
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(){
//创建类型A的structA
structA:= A {a:42,b:foo}
//转换为类型B
structB:= B {A:structA}
}
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)?
解决方案
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}
}
这篇关于Golang - 结构之间的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文