How can I convert between Go structs using field embedding?

Susan Sarandon
Release: 2024-10-27 01:58:30
Original
730 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!