将一个结构复制到另一个具有相同成员和不同类型的结构

将一个结构复制到另一个具有相同成员和不同类型的结构

问题描述:

我有两个具有相同成员的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.