Home > Backend Development > Golang > How to Assign Values Between Similar Go Structs with Different Types?

How to Assign Values Between Similar Go Structs with Different Types?

DDD
Release: 2024-12-13 20:32:18
Original
696 people have browsed it

How to Assign Values Between Similar Go Structs with Different Types?

Assigning Values Between Similar Structs with Distinct Types

Having structs with identical members but different types can create the need to transfer data between them. In such cases, a type conversion can provide a solution.

Consider the following struct definitions:

type Common struct {
    Gender int
    From   string
    To     string
}

type Foo struct {
    Id    string
    Name  string
    Extra Common
}

type Bar struct {
    Id    string
    Name  string
    Extra Common
}
Copy after login

To transfer values from a Foo struct to a Bar struct, you can use a type conversion:

foo := Foo{Id: "123", Name: "Joe"}
bar := Bar(foo)
Copy after login

In this case, the conversion works because the underlying types of Foo and Bar are identical except for their struct tags. The conversion automatically assigns the values of the Common member of foo to the corresponding member of bar.

For reference, a playground example is provided: [Playground Example](https://play.golang.org/p/FmF4FjJ0B4n)

The above is the detailed content of How to Assign Values Between Similar Go Structs with Different Types?. 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