Home >Backend Development >Golang >How Can I Efficiently Convert Between Go Structs with Identical Members but Different Types?
Converting Structs with Identical Members but Different Types
In Go, you may encounter situations where you have two structs with identical members but different types. This can pose a challenge when you need to copy the values from one struct to another.
Example Use Case
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 }
Suppose you have a variable foo of type Foo and you want to copy its values to a variable bar of type Bar.
Conversion Approach
Since the underlying types of Foo and Bar are identical except for struct tags, you can use a type conversion to copy the values. Here's how you can do it:
foo := Foo{Id: "123", Name: "Joe"} bar := Bar(foo)
In the above code, the conversion Bar(foo) explicitly converts the value of foo from type Foo to Bar. This is possible because the underlying types are identical.
Playground Example
<br>package main</p> <p>import "fmt"</p> <p>type Common struct {</p> <pre class="brush:php;toolbar:false">Gender int From string To string
}
type Foo struct {
Id string Name string Extra Common
}
type Bar struct {
Id string Name string Extra Common
}
func main() {
foo := Foo{Id: "123", Name: "Joe"} bar := Bar(foo) fmt.Println(bar)
}
Output
{123 Joe {0 "" ""}}
As you can see, the values from foo have been successfully copied to bar.
Note:
The conversion approach works only when the underlying types of the structs are identical except for struct tags. If the underlying types are different, you will need to manually copy the values member by member.
The above is the detailed content of How Can I Efficiently Convert Between Go Structs with Identical Members but Different Types?. For more information, please follow other related articles on the PHP Chinese website!