Home >Backend Development >Golang >How Can I Duplicate a Struct with Equivalent Members but Dissimilar Types in Go?

How Can I Duplicate a Struct with Equivalent Members but Dissimilar Types in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-12-11 18:47:14752browse

How Can I Duplicate a Struct with Equivalent Members but Dissimilar Types in Go?

Duplicating Structures with Equivalent Members and Dissimilar Types

Consider the following scenario: you have two distinct structs, Foo and Bar, each possessing identical members but differing in their underlying types. Your objective is to transfer the contents of one structure to the other.

In this instance, 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
}

Given instances foo of Foo and bar of Bar, how can bar be duplicated from foo?

Solution: Type Conversion

Since the fundamental types of Foo and Bar are structurally equivalent, a type conversion can be employed to alter the object type. The following code demonstrates how to copy a Foo value to a Bar value using conversion:

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

Type Compatibility Note

It's crucial to remember that this type conversion technique is only effective when the underlying types of the structures are essentially identical, save for any struct tags.

The above is the detailed content of How Can I Duplicate a Struct with Equivalent Members but Dissimilar 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