Go

Go

Made by DeepSource

Found manually copying of struct fields SCC-S1016

Anti-pattern
Major
Autofix

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.

Bad practice

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,
    }
}

Recommended

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)
}