首页 > 文章列表 > Golang:是否可以在不同的结构类型之间进行转换?

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

golang
381 2023-03-08

问题内容

假设我以这种方式设置了两种类似的类型:

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

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

谢谢。

正确答案

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

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