package util import ( "fmt" "math/rand" "reflect" "time" ) // IsNull 判断是否为空字符串 func IsNull(s string) string { if s == "" { return "0" } return s } // IsBlank 判断 reflect.Value 是否为空 func IsBlank(value reflect.Value) bool { switch value.Kind() { case reflect.String: return value.Len() == 0 case reflect.Bool: return !value.Bool() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return value.Int() == 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return value.Uint() == 0 case reflect.Float32, reflect.Float64: return value.Float() == 0 case reflect.Interface, reflect.Ptr: return value.IsNil() } return reflect.DeepEqual(value.Interface(), reflect.Zero(value.Type()).Interface()) } func GetNumString(num int64) string { if num < 10000 { return fmt.Sprintf("%v.00", num) } else if num >= 10000 && num < 100000000 { mean := float32(num) / float32(10000) str := fmt.Sprintf("%.1f", mean) return str + "万" } else { mean := float32(num) / float32(100000000) str := fmt.Sprintf("%.1f", mean) return str + "亿" } } func GetTimePoionter(t *time.Time) time.Time { if t == nil { return time.Now() } else { return *t } } func GetRandomString(l int) string { str := "0123456789" bytes := []byte(str) var result []byte r := rand.New(rand.NewSource(time.Now().UnixNano())) for i := 0; i < l; i++ { result = append(result, bytes[r.Intn(len(bytes))]) } return string(result) } func GetDayNum(inputType string, inputData int) (int, error) { result := 0 switch inputType { case "year": if inputData < 1 { fmt.Println("年份错误!") break } result = inputData case "month": months := []int{0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334} if (inputData <= 12) && (inputData < 0) { fmt.Println("月份错误!") break } result = months[inputData-1] case "day": if (inputData < 0) && (inputData > 31) { fmt.Println("日期错误!") break } result = inputData default: return 0, fmt.Errorf("输入参数非法:%s", inputType) } return result, nil } // RemoveRepByMap 通过map主键唯一的特性过滤重复元素 func RemoveRepByMap(slc []int64) []int64 { if len(slc) == 0 { return slc } var result []int64 tempMap := map[int64]byte{} // 存放不重复主键 for _, e := range slc { l := len(tempMap) tempMap[e] = 0 if len(tempMap) != l { // 加入map后,map长度变化,则元素不重复 result = append(result, e) } } return result } func RemoveStrRepByMap(slc []string) []string { if len(slc) == 0 { return slc } var result []string tempMap := map[string]byte{} // 存放不重复主键 for _, e := range slc { l := len(tempMap) tempMap[e] = 0 if len(tempMap) != l { // 加入map后,map长度变化,则元素不重复 result = append(result, e) } } return result }