Home > Article > Backend Development > How to Convert Between Go Structs with Different Fields?
Struct Conversion in Go
Q: I have two structs with different fields. How can I convert a variable of type A to type B, where A contains only essential fields and B contains additional fields? Is it possible to perform this conversion directly or do I need to manually copy fields?
A: In Go, struct conversion can be performed by leveraging the embedding feature. This allows you to nest the fields of one struct within another. For example, in your case, you have a struct A with two fields (a and b), and a struct B that embeds struct A and adds additional fields (c and potentially more).
To convert from A to B, you can simply create a B struct and embed an instance of A within it:
<code class="go">type A struct { a int b string } type B struct { A c string } func main() { // create structA of type A structA := A{a: 42, b: "foo"} // convert to type B structB := B{A: structA} // access the fields of structB fmt.Println(structB.a, structB.b, structB.c) // Output: 42 foo (additional value) }</code>
The above is the detailed content of How to Convert Between Go Structs with Different Fields?. For more information, please follow other related articles on the PHP Chinese website!