From ab64562b3d521912b6f999b520d656583a62d837 Mon Sep 17 00:00:00 2001 From: yuanzhao <2206582181@qq.com> Date: Wed, 8 Mar 2023 15:29:11 +0800 Subject: [PATCH] =?UTF-8?q?fea:=20=E8=BE=85=E5=8A=A9=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bootstrap/services/database/num.go | 62 ++++++++++++++++++++++++++++++ bootstrap/services/database/str.go | 2 + 2 files changed, 64 insertions(+) create mode 100644 bootstrap/services/database/num.go diff --git a/bootstrap/services/database/num.go b/bootstrap/services/database/num.go new file mode 100644 index 0000000..3b34e30 --- /dev/null +++ b/bootstrap/services/database/num.go @@ -0,0 +1,62 @@ +package database + +import ( + "fmt" + "math" + "strconv" +) + +// Int32 强制转换 +func Int32(v interface{}) int32 { + switch val := v.(type) { + case int32: + return val + case int: + return int32(val) + case int64: + return int32(val) + case float32: + return int32(val) + case float64: + return int32(val) + case string: + num, err := strconv.Atoi(val) + if err != nil { + // 无法解析为数字,返回 0 + return 0 + } + if num > math.MaxInt32 || num < math.MinInt32 { + // 超出 int32 的范围,返回 0 + return 0 + } + return int32(num) + default: + s := fmt.Sprintf("%d", v) + return Int32(s) + } +} + +// UInt32 强制转换 +func UInt32(v interface{}) uint32 { + switch val := v.(type) { + case uint32: + return val + case uint: + return uint32(val) + case uint64: + return uint32(val) + case float32: + return uint32(val) + case float64: + return uint32(val) + case string: + num, err := strconv.Atoi(val) + if err != nil { + return 0 + } + return uint32(num) + default: + s := fmt.Sprintf("%d", v) + return UInt32(s) + } +} diff --git a/bootstrap/services/database/str.go b/bootstrap/services/database/str.go index 10cd0f2..3a35ccf 100644 --- a/bootstrap/services/database/str.go +++ b/bootstrap/services/database/str.go @@ -1,5 +1,6 @@ package database +// StrPointer 字符串转指针 func StrPointer(str interface{}) *string { switch str.(type) { case string: @@ -15,6 +16,7 @@ func StrPointer(str interface{}) *string { return nil } +// IntPointer 转指针 func IntPointer(i interface{}) *int { switch i.(type) { case int: