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 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解