小编典典

Golang:是否可以在不同结构类型之间进行转换?

go

假设我有两种类似的设置方式:

type type1 []struct {
    Field1 string
    Field2 int
}
type type2 []struct {
    Field1 string
    Field2 int
}

是否有直接的方法将值从 type1 写入 type2,知道它们具有相同的字段?(除了编写一个将所有字段从源复制到目标的循环)


阅读 278

收藏
2021-12-20

共1个答案

小编典典

对于您的具体示例,您可以轻松转换它playground

t1 := type1{{"A", 1}, {"B", 2}}
t2 := type2(t1)
fmt.Println(t2)
2021-12-20