type BasicInfo struct { Name string`json:"name"` Age int`json:"age"` }
访问 StructTag
1 2 3 4 5
if nameField, ok := reflect.TypeOf(*e).FieldByName("Name"); !ok { t.Error("Failed to get 'Name' field.") } else { t.Log("Tag:format", nameField.Tag.Get("format")) }
funcFillBySettings(st interface{}, settings map[string]interface{})error { // func(v value) Elem() Value // elem returns the value that the interface v contains or that the pointer v points to. // It panics if v's Kind is not Interface or Ptr // It returns the zero Value if v is nil.
if reflect.TypeOf(st).Kind() != reflect.Ptr { // Elem() 获取指针指向的值 if reflect.TypeOf(st).Elem().Kind() != reflect.Struct { return errors.New("the first param should be a pointer to the struct type") } } if settings == nil { return errors.New("settings is nil") } var ( field reflect.StructField ok bool )
for k, v := range settings { if field, ok = (reflect.ValueOf(st)).Elem().Type().FieldByName(k); !ok { continue } if field.Type == reflect.TypeOf(v) { vstr := reflect.ValueOf(st) vstr = vstr.Elem() vstr.FieldByName(k).Set(reflect.ValueOf(v)) } } returnnil }