How can I convert between different struct types in Go?

DDD
Release: 2024-10-27 04:25:03
Original
781 people have browsed it

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

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

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!

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
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!