Home  >  Article  >  Backend Development  >  How to Convert Between Go Structs with Different Fields?

How to Convert Between Go Structs with Different Fields?

Linda Hamilton
Linda HamiltonOriginal
2024-10-28 04:14:02813browse

 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!

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