小编典典

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

go

假设我有两种类似的类型设置为:

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

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

谢谢。


阅读 254

收藏
2020-07-02

共1个答案

小编典典

对于您的特定示例,您可以轻松地将其转换playground

t1 := type1{{"A", 1}, {"B", 2}}
t2 := type2(t1)
fmt.Println(t2)
2020-07-02