vendredi 22 février 2019

Overwrite struct values using reflection in Golang

Given the following example (full code available here https://play.golang.org/p/TA_sr5DaxMu):

type Data struct {
    A int
    B int
    C sql.NullInt64
    D sql.NullFloat64
}

func main() {
    for i := 0; i < values1.NumField(); i++ {
        v1 := values1.Field(i).Interface()
        v2 := values2.Field(i).Interface()

        // name of the i-th Data struct field
        fieldName := values1.Type().Field(i).Name
        _ = fieldName

        switch v1 := v1.(type) {
        case int:
            if v1 == 0 {
                v1 = v2.(int)
                // struct1.fieldName = v1
            }
        case sql.NullInt64:
            if !v1.Valid {
                v1 = v2.(sql.NullInt64)
                // struct1.fieldName = v2.(sql.NullInt64)
            }
        case sql.NullFloat64:
            if !v1.Valid {
                v1 = v2.(sql.NullFloat64)
                // struct1.fieldName = v2.(sql.NullFloat64)
            }
        }
    }
}

I want to override zero values in struct1 from struct2 values.

I was trying an approach this by using reflect, and I'm no expert on this, but I was hoping there's some function that might accomplish what I commented inside the cases.

Is there a way to access the struct elements by its name, and be able to modify the value with another one?

Any help/advice will be appreciated.





Aucun commentaire:

Enregistrer un commentaire