💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## 调用反射填充对象 ~~~ // reflect.Ptr 指针 // reflect.Struct 结构体 func fillBySettings(obj interface{}, settings map[string]interface{}) error { if reflect.TypeOf(obj).Kind() != reflect.Ptr { return errors.New("st not ptr") } if reflect.TypeOf(obj).Elem().Kind() != reflect.Struct { return errors.New("st not struct") } if settings == nil { return errors.New("setting is nil") } var ok bool var field reflect.StructField for k, v := range settings { if field, ok = reflect.TypeOf(obj).Elem().FieldByName(k); !ok { continue } if field.Type == reflect.TypeOf(v) { reflect.ValueOf(obj).Elem().FieldByName(k).Set(reflect.ValueOf(v)) } } return nil } func TestReflectTypeOfInt(t *testing.T) { let := 10 t.Log(reflect.TypeOf(&let).Kind()) ff := 12.5 t.Log(reflect.TypeOf(&ff).Kind()) } func TestFillBySettings(t *testing.T) { r1 := 10 m1 := make(map[string]interface{}) if err := fillBySettings(&r1, m1); err != nil { t.Log(err) } stu := Student{} m2 := make(map[string]interface{}) m2["Name"] = "weiqiang" m2["Age"] = 20 m2["Weight"] = 60.5 if err := fillBySettings(&stu, m2); err != nil { t.Log(err) } else { t.Log("fill success:", stu) } } ~~~