feat: 字符串 -> 基础数据类型转换, 使用泛型实现

This commit is contained in:
2025-10-13 11:40:08 +08:00
parent 460672bcd0
commit 20d2912274
7 changed files with 515 additions and 6 deletions

50
op_string/base.go Normal file
View File

@ -0,0 +1,50 @@
// Package op_string ...
//
// Description : op_string ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2025-10-13 11:18
package op_string
import (
"git.zhangdeman.cn/zhangdeman/op_type"
"git.zhangdeman.cn/zhangdeman/wrapper/define"
"git.zhangdeman.cn/zhangdeman/wrapper/tool"
)
// ToBaseValue 转换为基础数据类型
func ToBaseValue[BaseType op_type.BaseType](str string) define.BaseValueResult[BaseType] {
var (
err error
target BaseType
)
if err = tool.ConvertAssign(&target, str); nil != err {
return define.BaseValueResult[BaseType]{
Value: target,
Err: err,
}
}
return define.BaseValueResult[BaseType]{
Value: target,
Err: err,
}
}
// ToBaseValuePtr 转换为基础数据类型指针
func ToBaseValuePtr[BaseType op_type.BaseType](str string) define.BaseValuePtrResult[BaseType] {
var (
err error
target BaseType
)
if err = tool.ConvertAssign(&target, str); nil != err {
return define.BaseValuePtrResult[BaseType]{
Value: nil,
Err: err,
}
}
return define.BaseValuePtrResult[BaseType]{
Value: &target,
Err: err,
}
}

32
op_string/base_test.go Normal file
View File

@ -0,0 +1,32 @@
// Package op_string ...
//
// Description : op_string ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2025-10-13 11:28
package op_string
import (
"reflect"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestToBaseValue(t *testing.T) {
Convey("测试ToBaseValue - uint64 转换成功", t, func() {
res := ToBaseValue[uint64]("12345")
So(res.Err, ShouldBeNil)
So(res.Value, ShouldEqual, uint64(12345))
So(reflect.TypeOf(res.Value).Kind(), ShouldEqual, reflect.Uint64)
So(reflect.TypeOf(res.Value).Kind(), ShouldNotEqual, reflect.Uint32)
})
Convey("测试ToBaseValue - uint64 转换失败", t, func() {
res := ToBaseValue[uint64]("s12345")
So(res.Err, ShouldNotBeNil)
So(res.Value, ShouldEqual, 0)
So(reflect.TypeOf(res.Value).Kind(), ShouldEqual, reflect.Uint64)
So(reflect.TypeOf(res.Value).Kind(), ShouldNotEqual, reflect.Uint32)
})
}