动态修改Golang struct {}值上的属性,另外

时间:2018-10-28 03:53:06

标签: go

我在路由器处理程序中有此代码

pip

但是我想使它动态化,像这样:

    decoder := json.NewDecoder(r.Body)
    var t person.Model
    err := decoder.Decode(&t).          // t is a struct value
    item, ok := v.People[params["id"]]. // ok is a struct value

    if t.Handle != "" {
        item.Handle = t.Handle
    }

    if t.Work != "" {
        item.Work = t.Work
    }

    if t.Image != "" {
        item.Image = t.Image
    }

    if t.Firstname != "" {
        item.Firstname = t.Firstname
    }

    if t.Lastname != "" {
        item.Lastname = t.Lastname
    }

    if t.Email != "" {
        item.Email = t.Email
    }

Golang有可能吗?

1 个答案:

答案 0 :(得分:1)

为此使用reflect包:

func setFields(dst, src interface{}, names ...string) {
    d := reflect.ValueOf(dst).Elem()
    s := reflect.ValueOf(src).Elem()
    for _, name := range names {
        df := d.FieldByName(name)
        sf := s.FieldByName(name)
        switch sf.Kind() {
        case reflect.String:
            if v := sf.String(); v != "" {
                df.SetString(v)
            }
            // handle other kinds
        }
    }
}

使用指向值的指针进行调用:

setFields(&item, &t, "FirstName", "LastName", "Email", "Handle")

Playground example

如果您的实际目标是仅覆盖JSON中存在的字段,请执行以下操作:

item, ok := v.People[params["id"]]. 
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&item)

Playground example