将一个结构复制到另一个具有相同成员和不同类型的结构 [英] Copy one struct to another where structs have same members and different types

查看:61
本文介绍了将一个结构复制到另一个具有相同成员和不同类型的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个具有相同成员的struct,我想将一个结构复制到另一个结构,请参见下面的伪代码:

I have two struct having the same members, I want to copy one struct to another, see the pseudo code below:

type Common struct {
    Gender int
    From   string
    To     string
}

type Foo struct {
    Id    string
    Name  string
    Extra Common
}

type Bar struct {
    Id    string
    Name  string
    Extra Common
}

然后我有结构Foofoo和结构Barbar,有什么方法可以从foo复制bar吗?

Then I have foo of struct Foo, and bar of struct Bar, Is there any way to copy bar from foo?

推荐答案

使用转换进行更改类型.以下代码使用转换将类型为Foo的值复制到类型为Bar的值:

Use a conversion to change the type. The following code uses a conversion to copy a value of type Foo to a value of type Bar:

foo := Foo{Id: "123", Name: "Joe"}
bar := Bar(foo)

游乐场示例

转换仅在基础类型相同(结构标记除外)时起作用.

The conversion only works when the underlying types are identical except for struct tags.

这篇关于将一个结构复制到另一个具有相同成员和不同类型的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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