// Package utils 提供通用工具函数 package utils import ( "fmt" "strconv" "time" ) // ToString 将任意类型转换为字符串 // 支持 []byte, string, int/int32/int64, uint/uint32/uint64, float32/float64, bool, time.Time func ToString(v interface{}) string { switch t := v.(type) { case []byte: return string(t) case string: return t case int64: return strconv.FormatInt(t, 10) case int32: return strconv.FormatInt(int64(t), 10) case int: return strconv.Itoa(t) case uint64: return strconv.FormatUint(t, 10) case uint32: return strconv.FormatUint(uint64(t), 10) case uint: return strconv.FormatUint(uint64(t), 10) case float64: // 对于整数部分,使用整数格式;对于小数部分,保留必要精度 if t == float64(int64(t)) { return strconv.FormatInt(int64(t), 10) } return strconv.FormatFloat(t, 'f', -1, 64) case float32: // 对于整数部分,使用整数格式;对于小数部分,保留必要精度 if t == float32(int64(t)) { return strconv.FormatInt(int64(t), 10) } return strconv.FormatFloat(float64(t), 'f', -1, 32) case bool: if t { return "1" } return "0" case time.Time: return t.Format("2006-01-02 15:04:05") case nil: return "" default: // 尝试使用 fmt.Sprintf 作为兜底 if s := fmt.Sprintf("%v", t); s != "" { return s } return "" } }