Struct Conversion in Go
In Go, structs provide a convenient way to represent data with named fields. However, situations may arise where one needs to convert structs of different types.
Consider the following example:
<code class="go">type A struct { a int b string } type B struct { A c string // more fields }</code>
Suppose you have a variable of type A and want to convert it to type B. Is there a built-in mechanism for this conversion in Go?
The answer is yes. In Go, struct fields can be embedded, allowing for easy conversion between structs. In the example above, B embeds A, which means it contains all the fields of A as its own fields.
To convert a variable of type A to type B, you can simply assign the value of A to the embedded A field in B. Here's how:
<code class="go">func main() { // create structA of type A structA := A{a: 42, b: "foo"} // convert to type B structB := B{A: structA} }</code>
This code assigns the value of structA to the embedded A field in structB, effectively converting structA to type B.
The above is the detailed content of How can I convert between different struct types in Go?. For more information, please follow other related articles on the PHP Chinese website!