Home  >  Article  >  Backend Development  >  How can I convert between Go structs using field embedding?

How can I convert between Go structs using field embedding?

Susan Sarandon
Susan SarandonOriginal
2024-10-27 01:58:30731browse

How can I convert between Go structs using field embedding?

Converting Between Go Structs

When working with multiple structs, it is often necessary to convert data from one struct to another. In Go, this can be achieved through a technique called field embedding.

Consider the following code snippet:

<code class="go">type A struct {
    a int
    b string
}

type B struct {
    A // field embedding of A
    c string
    // more fields
}</code>

In this example, struct B embeds struct A. This means that struct B contains all the fields of struct A in addition to its own fields.

To convert a value of type A to type B, you can simply assign the fields of A to those of B. For instance:

<code class="go">func main() {
    structA := A{a: 42, b: "foo"}

    // assign structA to the embedded A field of structB
    structB := B{A: structA}
}</code>

Through field embedding, you can easily convert between structs, eliminating the need to manually copy fields or create conversion methods.

The above is the detailed content of How can I convert between Go structs using field embedding?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn