Golang:是否可以在不同的结构类型之间进行转换? [英] Golang : Is conversion between different struct types possible?

查看:160
本文介绍了Golang:是否可以在不同的结构类型之间进行转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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



谢谢。

playground

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

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


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
}

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)

Thanks.

解决方案

For your specific example, you can easily convert it playground:

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

这篇关于Golang:是否可以在不同的结构类型之间进行转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆