如何选择在运行时更新哪个结构成员?
How can I choose which struct member to update at runtime?
假设我在 Go 中有一个如下所示的结构:
LastUpdate struct {
Name string `yaml:"name"`
Address string `yaml:"address"`
Phone string `yaml:"phone"`
}
现在假设我想创建一个接受字段名称的函数(例如 "Phone"),然后将该字段更新为一个值,例如今天的日期。
我怎样才能以接受字段名称并在结构中更新该字段的方式构建函数?
我知道我可以为每个场景做一个 IF 子句 (if field == "Phone") {var.LastUpdate.Phone = time.Now().Date()},但是我我想构建这个函数,这样我以后每次向这个结构添加新成员时就不必去添加 IF 子句。想法?
使用 reflect 包按名称设置字段。
// setFieldByName sets field with given name to specified value.
// The structPtr argument must be a pointer to a struct. The
// value argument must be assignable to the field.
func setFieldByName(structPtr interface{}, name string, value interface{}) error {
v := reflect.ValueOf(structPtr)
v = v.Elem() // deference pointer
v = v.FieldByName(name) // get field with specified name
if !v.IsValid() {
return errors.New("field not found")
}
v.Set(reflect.ValueOf(value))
return nil
}
这样使用:
var lu LastUpdate
setFieldByName(&lu, "Name", "Russ Cox")
假设我在 Go 中有一个如下所示的结构:
LastUpdate struct {
Name string `yaml:"name"`
Address string `yaml:"address"`
Phone string `yaml:"phone"`
}
现在假设我想创建一个接受字段名称的函数(例如 "Phone"),然后将该字段更新为一个值,例如今天的日期。
我怎样才能以接受字段名称并在结构中更新该字段的方式构建函数?
我知道我可以为每个场景做一个 IF 子句 (if field == "Phone") {var.LastUpdate.Phone = time.Now().Date()},但是我我想构建这个函数,这样我以后每次向这个结构添加新成员时就不必去添加 IF 子句。想法?
使用 reflect 包按名称设置字段。
// setFieldByName sets field with given name to specified value.
// The structPtr argument must be a pointer to a struct. The
// value argument must be assignable to the field.
func setFieldByName(structPtr interface{}, name string, value interface{}) error {
v := reflect.ValueOf(structPtr)
v = v.Elem() // deference pointer
v = v.FieldByName(name) // get field with specified name
if !v.IsValid() {
return errors.New("field not found")
}
v.Set(reflect.ValueOf(value))
return nil
}
这样使用:
var lu LastUpdate
setFieldByName(&lu, "Name", "Russ Cox")