将一个结构复制到另一个具有相同成员和不同类型的结构
问题描述:
我有两个具有相同成员的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
}
然后我有结构Foo
的foo
和结构Bar
的bar
,有什么方法可以从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.