package utils import ( "fmt" "reflect" "strconv" ) // HasPrefix 判断字符串是否以指定前缀开头 func HasPrefix(s *string, prefix string) bool { pl := len(prefix) return len(*s) >= pl && (*s)[:pl] == prefix } // IsPrefix 检查字符串 s 是否以 prefix 开头,并返回一个新的字符串, // 如果 s 不以 prefix 开头,则在 s 前面添加 prefix。 func IsPrefix(s, prefix string) string { if s == "" || prefix == "" { return s + prefix } if HasPrefix(&s, prefix) { return s } return prefix + s } // HasSuffix 判断字符串是否以指定后缀结尾 func HasSuffix(s *string, suffix string) bool { if s == nil { return false } return len(*s) >= len(suffix) && (*s)[len(*s)-len(suffix):] == suffix } // IsSuffix 检查字符串 s 是否以 suffix 结尾,并返回一个新的字符串, // 如果 s 不以 suffix 结尾,则在 s 后面添加 suffix。 func IsSuffix(s, suffix string) string { if s == "" || suffix == "" { return s + suffix } if HasSuffix(&s, suffix) { return s } return s + suffix } func ToString(i interface{}) (string, error) { value := reflect.ValueOf(i) switch value.Kind() { case reflect.String: return value.String(), nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return strconv.FormatInt(value.Int(), 10), nil case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return strconv.FormatUint(value.Uint(), 10), nil case reflect.Float32, reflect.Float64: return strconv.FormatFloat(value.Float(), 'g', -1, 64), nil case reflect.Bool: return strconv.FormatBool(value.Bool()), nil default: return "", fmt.Errorf("无法将 %s 类型转换为 string", value.Type()) } }