Struct Conversion in Go
Consider the following two structs:
type A struct { a int b string } type B struct { A c string }
Suppose you have a variable of type A and want to convert it to type B. Is this possible in Go, or do you need to manually copy fields or create an explicit conversion method?
Method 1: Embedded Struct Assignment
As you mentioned in your question, embedding can be utilized for this purpose. By embedding A in B, you can convert a variable of type A to type B simply by assigning it to the embedded field. For example:
func main() { structA := A{a: 42, b: "foo"} structB := B{A: structA} // Embed structA into structB }
This approach creates a new instance of B that contains the data from A in its embedded field.
Method 2: Manual Field Copying
Alternatively, you can manually copy the fields from A to B as follows:
func main() { structA := A{a: 42, b: "foo"} structB := B{ A: structA, // Copy fields from structA c: "bar", } }
This method involves creating a new instance of B and manually assigning the fields from A.
Method 3: Explicit Conversion Method
Another option is to create an explicit conversion method that converts A to B. This could be useful if you have a complex conversion logic. However, this approach is not necessary in this case, as the above methods provide a straightforward way to achieve the desired conversion.
The above is the detailed content of How to Convert a Struct in Go: Embedding, Manual Copying, or Explicit Conversion?. For more information, please follow other related articles on the PHP Chinese website!