How to Convert a Struct in Go: Embedding, Manual Copying, or Explicit Conversion?

Susan Sarandon
Release: 2024-10-29 01:40:02
Original
733 people have browsed it

How to Convert a Struct in Go: Embedding, Manual Copying, or Explicit Conversion?

Struct Conversion in Go

Consider the following two structs:

type A struct {
    a int
    b string
}

type B struct {
    A
    c string
}
Copy after login

Suppose you have a variable of type A and want to convert it to type B. Is this possible in Go, or do you need to manually copy fields or create an explicit conversion method?

Method 1: Embedded Struct Assignment

As you mentioned in your question, embedding can be utilized for this purpose. By embedding A in B, you can convert a variable of type A to type B simply by assigning it to the embedded field. For example:

func main() {
    structA := A{a: 42, b: "foo"}
    structB := B{A: structA} // Embed structA into structB
}
Copy after login

This approach creates a new instance of B that contains the data from A in its embedded field.

Method 2: Manual Field Copying

Alternatively, you can manually copy the fields from A to B as follows:

func main() {
    structA := A{a: 42, b: "foo"}
    structB := B{
        A: structA, // Copy fields from structA
        c: "bar",
    }
}
Copy after login

This method involves creating a new instance of B and manually assigning the fields from A.

Method 3: Explicit Conversion Method

Another option is to create an explicit conversion method that converts A to B. This could be useful if you have a complex conversion logic. However, this approach is not necessary in this case, as the above methods provide a straightforward way to achieve the desired conversion.

The above is the detailed content of How to Convert a Struct in Go: Embedding, Manual Copying, or Explicit Conversion?. 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