dongrou839975 2015-05-27 18:33
浏览 26
已采纳

从REST API调用更新对象-结构合并?

I have a JSON REST API accepting sparse updates, but the pattern I've come up with seems exceptionally verbose. Am I going about this the wrong way?

(Assume this is using a data store with no sparse update support built in.)

func choose(a, b *string) *string {
    if a != nil {
        return a
    }
    return b
}

type Model {
    Id     *string `json:"id"`
    Field1 *string `json:"field1"`
    Field2 *string `json:"field2"`
    Field3 *string `json:"field3"`
    ...
}

func (m1 Model) Update(m2 Model) (m3 Model) {
    m3.Id = choose(m2.Id, m1.Id)
    m3.Field1 = choose(m2.Field1, m1.Field1)
    m3.Field2 = choose(m2.Field2, m1.Field2)
    m3.Field3 = choose(m2.Field3, m1.Field3)
    ...
    return
}

func UpdateController(input Model) error {
    previous, _ := store.Get(*input.Id)
    updated := previous.Update(input)
    return store.Put(updated)
}

Ideally I'd be able to write UpdateController like this instead:

func UpdateController(input Model) {
    previous, _ := store.Get(*input.Id)
    updated, _ := structs.Update(previous, input)
    return store.Put(updated)
}

(Error-handling elided for clarity.)

  • 写回答

3条回答 默认 最新

  • douyingbei1458 2015-05-27 19:24
    关注

    Well, if you are open to using reflection, the problem becomes fairly simple:

    http://play.golang.org/p/dc-OnO1cZ4

    func (m1 Model) Update(m2 Model) (m3 Model) {
        old := reflect.ValueOf(m1)
        new := reflect.ValueOf(m2)
        final := reflect.ValueOf(&m3).Elem()
        for i := 0; i < old.NumField(); i++ {
            if !new.Field(i).IsNil()  {
               final.Field(i).Set(new.Field(i))
            } else {
               final.Field(i).Set(old.Field(i))
            }      
        }
        return
    }
    

    The reason we do reflect.ValueOf(&m3).Elem() is that v3 needs to be settable, see http://blog.golang.org/laws-of-reflection

    But basically, by using reflection, we can loop through the struct fields, see if the updated one is nil, and if so, we use the old value.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看