// Package convertx 提供带默认值兜底的类型转换工具, // 基于 gconv 构建。 // // 注意:gconv 转换失败时静默返回零值, // 因此本工具仅对 nil / 空字符串输入回退到默认值。 // 需要严格转换时请传入已校验的数据。 package convertx import ( "strings" "github.com/gogf/gf/v2/util/gconv" ) // ToInt 将 v 转为 int,v 为 nil 或空字符串时返回 def。 func ToInt(v any, def int) int { if isEmpty(v) { return def } return gconv.Int(v) } // ToInt64 将 v 转为 int64,v 为 nil 或空字符串时返回 def。 func ToInt64(v any, def int64) int64 { if isEmpty(v) { return def } return gconv.Int64(v) } // ToFloat64 将 v 转为 float64,v 为 nil 或空字符串时返回 def。 func ToFloat64(v any, def float64) float64 { if isEmpty(v) { return def } return gconv.Float64(v) } // ToString 将 v 转为 string,v 为 nil 时返回 def。 func ToString(v any, def string) string { if v == nil { return def } return gconv.String(v) } // ToBool 将 v 转为 bool,v 为 nil 或空字符串时返回 def。 func ToBool(v any, def bool) bool { if isEmpty(v) { return def } return gconv.Bool(v) } // isEmpty 判断 v 是否为 nil 或空字符串。 func isEmpty(v any) bool { if v == nil { return true } if s, ok := v.(string); ok { return strings.TrimSpace(s) == "" } return false }