feat: 增加map类型转换
This commit is contained in:
31
op_string/map.go
Normal file
31
op_string/map.go
Normal file
@ -0,0 +1,31 @@
|
||||
// Package op_string ...
|
||||
//
|
||||
// Description : op_string ...
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 2025-10-13 12:18
|
||||
package op_string
|
||||
|
||||
import (
|
||||
"git.zhangdeman.cn/zhangdeman/serialize"
|
||||
"git.zhangdeman.cn/zhangdeman/wrapper/define"
|
||||
)
|
||||
|
||||
// ToMap 转换为map, 数据类型可比较, 即可作为 map key, 内置 any 类型无法作为key
|
||||
func ToMap[Key comparable, Value comparable](str string) define.MapValueResult[Key, Value] {
|
||||
var (
|
||||
err error
|
||||
res map[Key]Value
|
||||
)
|
||||
if err = serialize.JSON.UnmarshalWithNumberForString(str, &res); err != nil {
|
||||
return define.MapValueResult[Key, Value]{
|
||||
Value: nil,
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return define.MapValueResult[Key, Value]{
|
||||
Value: res,
|
||||
Err: nil,
|
||||
}
|
||||
}
|
30
op_string/map_test.go
Normal file
30
op_string/map_test.go
Normal file
@ -0,0 +1,30 @@
|
||||
// Package op_string ...
|
||||
//
|
||||
// Description : op_string ...
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 2025-10-13 12:21
|
||||
package op_string
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"encoding/json"
|
||||
|
||||
. "github.com/smartystreets/goconvey/convey"
|
||||
)
|
||||
|
||||
func TestToMap(t *testing.T) {
|
||||
Convey("map[string]any转换成", t, func() {
|
||||
testData := `{
|
||||
"name": "baicha",
|
||||
"age": 18
|
||||
}`
|
||||
res := ToMap[string, any](testData)
|
||||
So(res.Err, ShouldBeNil)
|
||||
So(res.Value, ShouldNotBeNil)
|
||||
So(res.Value["name"], ShouldEqual, "baicha")
|
||||
So(res.Value["age"], ShouldEqual, json.Number("18"))
|
||||
})
|
||||
}
|
Reference in New Issue
Block a user