Copying Structs with Identical Members and Different Types
In Go, it is possible to encounter situations where two structs share the same members but have different types. For instance, 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 }
Given an instance of Foo (named foo) and an instance of Bar (named bar), can we copy the values from foo to bar?
Solution Using Type Conversion
Since the underlying types of Foo and Bar are identical except for struct tags, we can leverage a type conversion to change the type. This involves the following steps:
foo := Foo{Id: "123", Name: "Joe"} bar := Bar(foo)
Playground Example
You can test this solution on the Go Playground:
https://go.dev/play/p/j5jL1XFs-zG
Note: The conversion only works when the underlying types are identical except for struct tags. Complex types such as maps, slices, or arrays within a struct require a more detailed approach for copying values.
The above is the detailed content of Can Go's type conversion copy values between structs with identical members but different types?. For more information, please follow other related articles on the PHP Chinese website!