Golang:是否可以在不同结构类型之间进行转换? [英] Golang : Is conversion between different struct types possible?
本文介绍了Golang:是否可以在不同结构类型之间进行转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有两种类似的设置方式:
Let's say I have two similar types set this way :
type type1 []struct {
Field1 string
Field2 int
}
type type2 []struct {
Field1 string
Field2 int
}
是否有直接的方法将值从类型 1 写入类型 2,并且知道它们具有相同的字段?(除了编写一个将所有字段从源复制到目标的循环)
Is there a direct way to write values from a type1 to a type2, knowing that they have the same fields ? (other than writing a loop that will copy all the fields from the source to the target)
谢谢.
推荐答案
对于您的具体示例,您可以轻松转换它游乐场:
For your specific example, you can easily convert it playground:
t1 := type1{{"A", 1}, {"B", 2}}
t2 := type2(t1)
fmt.Println(t2)
这篇关于Golang:是否可以在不同结构类型之间进行转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文