-
// 检测结构体/map中指定参数不能为空 func CheckValueNotEmpty(obj interface{}, fields []string) (bool, error) { objValue := reflect.ValueOf(obj) switch reflect.ValueOf(obj).Kind() { case reflect.Struct: for _, field := range fields { value := objValue.FieldByName(field) if false == value.IsValid() || value.Interface() == "" { msg := field + ",不能为空" err := errors.New(msg) return false, err } } case reflect.Map: for _, field := range fields { value := objValue.MapIndex(reflect.ValueOf(field)) if false == value.IsValid() || value.Interface() == "" { msg := field + ",不能为空" err := errors.New(msg) return false, err } } } return true, nil }
-
使用案例: fields := []string{"Age", "Sex", "Weight" , "Height"} // 结构体使用 type Test2 struct { Age int `json:"age"` Sex string `json:"sex"` Height string `json:"height"` Weight string `json:"weight"` } data := Test2{ Sex: "女", Weight: "11.2", } // map使用 //data := map[string]string{"Sex": "男", "Weight": "112"} // 方法调用 _, err := CheckValueNotEmpty(data, fields) if err != nil { fmt.Println(err) }
检测结构体、map中,指定的key的值是否为空
最新推荐文章于 2023-08-22 14:00:58 发布