Two struct types with identical fields can be converted, and hence a manual copy of struct fields could be avoided with the help of type conversion.
In older versions of Go, the fields had identical struct tags. Since Go 1.8; however, struct tags are ignored during conversions, and thus, it is not necessary to manually copy every field individually.
type T1 struct {
Field1 string `json:"field1"`
Field2 string `json:"field2"`
}
// Tag names have an underscore (_) in middle
type T2 struct {
Field1 string `json:"field_1"`
Field2 string `json:"field_2"`
}
func foo() {
x := T1{
Field1: "field1",
Field2: "field2",
}
// Manual copying. Not required from Go 1.8 onwards
y := T2{
Field1: x.Field1,
Field2: x.Field2,
}
}
type T1 struct {
Field1 string `json:"field1"`
Field2 string `json:"field2"`
}
// Tag names have an underscore (_) in middle
type T2 struct {
Field1 string `json:"field_1"`
Field2 string `json:"field_2"`
}
func foo() {
x := T1{
Field1: "field1",
Field2: "field2",
}
// Removes the need to copy every field manually.
// Requires Go v1.8+
y := T2(x)
}