Home  >  Article  >  Backend Development  >  How can I convert between different struct types in Go?

How can I convert between different struct types in Go?

DDD
DDDOriginal
2024-10-27 04:25:03764browse

How can I convert between different struct types in Go?

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!

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