Assigning Values Between Similar Structs with Distinct Types
Having structs with identical members but different types can create the need to transfer data between them. In such cases, a type conversion can provide a solution.
Consider the following struct definitions:
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 }
To transfer values from a Foo struct to a Bar struct, you can use a type conversion:
foo := Foo{Id: "123", Name: "Joe"} bar := Bar(foo)
In this case, the conversion works because the underlying types of Foo and Bar are identical except for their struct tags. The conversion automatically assigns the values of the Common member of foo to the corresponding member of bar.
For reference, a playground example is provided: [Playground Example](https://play.golang.org/p/FmF4FjJ0B4n)
The above is the detailed content of How to Assign Values Between Similar Go Structs with Different Types?. For more information, please follow other related articles on the PHP Chinese website!