service.xpcool.com/common/tools/convertx/convertx.go
夏犀麟 8d5f2c65ae feat(common): 新增公共模块 common/tools 及项目上下文记忆体系
- common/tools 工具模块,10 个子功能:md5/cryptox/uuid/random/timex/convertx/strx/slicex/ip/filex(薄封装 GoFrame 内置组件)
- AGENTS.md 项目智能体说明书(架构、规范、命令、记忆体系索引)
- docs/change-log/2026-08-24.md 本次请求与变更记录
- .gitignore 排除 .workbuddy/;PROJECT_STRUCTURE.md 补充目录树
2026-08-24 17:18:10 +08:00

65 lines
1.4 KiB
Go

// Package convertx provides type conversion helpers with default-value
// fallback, built on top of gconv.
//
// Note: gconv silently returns the zero value when conversion fails, so the
// helpers here only fall back to the default for nil / blank-string inputs.
// Pass pre-validated data when strict conversion is required.
package convertx
import (
"strings"
"github.com/gogf/gf/v2/util/gconv"
)
// ToInt converts v to int, returning def when v is nil or a blank string.
func ToInt(v any, def int) int {
if isEmpty(v) {
return def
}
return gconv.Int(v)
}
// ToInt64 converts v to int64, returning def when v is nil or a blank string.
func ToInt64(v any, def int64) int64 {
if isEmpty(v) {
return def
}
return gconv.Int64(v)
}
// ToFloat64 converts v to float64, returning def when v is nil or a blank string.
func ToFloat64(v any, def float64) float64 {
if isEmpty(v) {
return def
}
return gconv.Float64(v)
}
// ToString converts v to string, returning def when v is nil.
func ToString(v any, def string) string {
if v == nil {
return def
}
return gconv.String(v)
}
// ToBool converts v to bool, returning def when v is nil or a blank string.
func ToBool(v any, def bool) bool {
if isEmpty(v) {
return def
}
return gconv.Bool(v)
}
// isEmpty reports whether v is nil or a blank string.
func isEmpty(v any) bool {
if v == nil {
return true
}
if s, ok := v.(string); ok {
return strings.TrimSpace(s) == ""
}
return false
}