From efab8cb6d293a6c7fed63e47bb28abb15995a868 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Mon, 13 Oct 2025 14:20:40 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20str=E8=BD=ACstruct?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- define/result.go | 8 +++++++- op_string/map.go | 19 ++++++++++++++++++- op_string/map_test.go | 20 ++++++++++++++++++++ 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/define/result.go b/define/result.go index b1d176c..7f26b04 100644 --- a/define/result.go +++ b/define/result.go @@ -22,7 +22,13 @@ type BaseValuePtrResult[BaseType op_type.BaseType] struct { } // MapValueResult map类型转换结果 -type MapValueResult[Key comparable, Value comparable] struct { +type MapValueResult[Key comparable, Value any] struct { Value map[Key]Value `json:"result"` // 转换结果 Err error `json:"err"` // 错误信息 } + +// StructValueResult struct类型转换结果 +type StructValueResult[Value any] struct { + Value Value `json:"result"` // 转换结果 + Err error `json:"err"` // 错误信息 +} diff --git a/op_string/map.go b/op_string/map.go index 0c00720..189cdb2 100644 --- a/op_string/map.go +++ b/op_string/map.go @@ -13,7 +13,7 @@ import ( ) // ToMap 转换为map, 数据类型可比较, 即可作为 map key, 内置 any 类型无法作为key -func ToMap[Key comparable, Value comparable](str string) define.MapValueResult[Key, Value] { +func ToMap[Key comparable, Value any](str string) define.MapValueResult[Key, Value] { var ( err error res map[Key]Value @@ -29,3 +29,20 @@ func ToMap[Key comparable, Value comparable](str string) define.MapValueResult[K Err: nil, } } + +// ToStruct 转换为结构体 +func ToStruct[Value any](str string, receiver Value) define.StructValueResult[Value] { + var ( + err error + ) + if err = serialize.JSON.UnmarshalWithNumberForString(str, receiver); err != nil { + return define.StructValueResult[Value]{ + Value: receiver, + Err: err, + } + } + return define.StructValueResult[Value]{ + Value: receiver, + Err: nil, + } +} diff --git a/op_string/map_test.go b/op_string/map_test.go index 9dcef82..d2b8441 100644 --- a/op_string/map_test.go +++ b/op_string/map_test.go @@ -28,3 +28,23 @@ func TestToMap(t *testing.T) { So(res.Value["age"], ShouldEqual, json.Number("18")) }) } + +func TestToStruct(t *testing.T) { + Convey("struct转换成", t, func() { + testData := `{ + "name": "baicha", + "age": 18 + }` + + type User struct { + Name string `json:"name"` + Age int `json:"age"` + } + var u User + res := ToStruct(testData, &u) + So(res.Err, ShouldBeNil) + So(res.Value, ShouldNotBeNil) + So(res.Value.Name, ShouldEqual, "baicha") + So(res.Value.Age, ShouldEqual, 18) + }) +}