Home >Backend Development >Golang >How to Convert Between Go Structs with Embedded Structures?
Conversion Between Go Structs
In Go, structs offer a convenient way to organize and represent data. However, converting between structs of different types can sometimes be necessary. Consider the following scenario:
You have two structs, A and B, where A contains only a few essential fields, while B holds additional fields and inherits all fields from A. You want to convert a variable of type A into type B without manually copying the values.
Solution
Go provides a straightforward way to achieve this type of conversion:
<code class="go">package main type A struct { a int b string } type B struct { A c string // Additional fields } func main() { // Create a variable of type A structA := A{a: 42, b: "foo"} // Convert structA to type B using embedded struct structB := B{A: structA} }</code>
In this example, the B struct embeds an instance of A using its anonymous field. When converting structA to structB, the fields of structA are automatically assigned to the corresponding fields in structB, including the c field that was not present in A. This allows you to construct a complete B structure from an existing A variable effortlessly.
The above is the detailed content of How to Convert Between Go Structs with Embedded Structures?. For more information, please follow other related articles on the PHP Chinese website!