duancao1951 2019-02-22 21:05
浏览 23

在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 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.

EDIT: the real structure has more than 40 fields, that's the reason I'm iterating over all the struct fields by their index.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 2024-五一综合模拟赛
    • ¥15 下图接收小电路,谁知道原理
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度
    • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
    • ¥15 ETLCloud 处理json多层级问题
    • ¥15 matlab中使用gurobi时报错
    • ¥15 这个主板怎么能扩出一两个sata口
    • ¥15 不是,这到底错哪儿了😭