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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3