Home > Backend Development > Golang > How Can I Efficiently Transfer Data Between Go Structs with Identical Members but Different Types?

How Can I Efficiently Transfer Data Between Go Structs with Identical Members but Different Types?

Patricia Arquette
Release: 2024-12-10 02:18:13
Original
474 people have browsed it

How Can I Efficiently Transfer Data Between Go Structs with Identical Members but Different Types?

Copy Structs with Identical Members and Variant Types

In Go, it's not uncommon to have structs with identical members but differing types. Consider the following example:

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

Given an instance of Foo and Bar, how can we transfer data from one to the other?

Solution: Conversion

Since the underlying types of Foo and Bar are identical apart from struct tags, Go offers a straightforward solution: conversion. By converting the Foo value to type Bar, we effectively overwrite the existing data in Bar. Here's the code:

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

Example

Let's test the conversion in a playground example: https://go.dev/play/p/1W3EXQVXVhS.

Limitations

It's worth noting that conversion only works when the underlying types are the same except for struct tags. If the underlying types differ significantly, creating a dedicated copy function would be necessary.

The above is the detailed content of How Can I Efficiently Transfer Data Between Go Structs with Identical Members but 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template