Home > Backend Development > Golang > Can Go's type conversion copy values between structs with identical members but different types?

Can Go's type conversion copy values between structs with identical members but different types?

Patricia Arquette
Release: 2024-12-13 03:39:09
Original
469 people have browsed it

Can Go's type conversion copy values between structs with identical members but different types?

Copying Structs with Identical Members and Different Types

In Go, it is possible to encounter situations where two structs share the same members but have different types. For 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
}
Copy after login

Given an instance of Foo (named foo) and an instance of Bar (named bar), can we copy the values from foo to bar?

Solution Using Type Conversion

Since the underlying types of Foo and Bar are identical except for struct tags, we can leverage a type conversion to change the type. This involves the following steps:

  1. Declare a variable of type Foo named foo.
  2. Declare a variable of type Bar named bar.
  3. Assign the value of foo to bar using a type conversion.
foo := Foo{Id: "123", Name: "Joe"}
bar := Bar(foo)
Copy after login

Playground Example

You can test this solution on the Go Playground:
https://go.dev/play/p/j5jL1XFs-zG

Note: The conversion only works when the underlying types are identical except for struct tags. Complex types such as maps, slices, or arrays within a struct require a more detailed approach for copying values.

The above is the detailed content of Can Go's type conversion copy values between 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