From 5a536794003320f2069dd04c3d19b49c68a9b8b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Tue, 23 Jan 2024 10:42:03 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96toAnySlice?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- define.go | 20 ++++++++++---------- string.go | 25 +++++++++++++++++++++++-- string_test.go | 6 ++++++ 3 files changed, 39 insertions(+), 12 deletions(-) diff --git a/define.go b/define.go index f1368b2..5a21d40 100644 --- a/define.go +++ b/define.go @@ -472,16 +472,6 @@ type StringSliceResult struct { Err error } -// AnySliceResult ... -// -// Author : go_developer@163.com<白茶清欢> -// -// Date : 18:28 2023/5/8 -type AnySliceResult struct { - Value []interface{} - Err error -} - // MapResult 转map的结果 // // Author : go_developer@163.com<白茶清欢> @@ -491,3 +481,13 @@ type MapResult struct { Value Map Err error } + +// AnySliceResult ... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 18:28 2023/5/8 +type AnySliceResult struct { + Value []interface{} + Err error +} diff --git a/string.go b/string.go index 596ca3f..4aaa19b 100644 --- a/string.go +++ b/string.go @@ -990,13 +990,34 @@ func (str String) ToStringSlice(splitChar ...string) StringSliceResult { // Author : go_developer@163.com<白茶清欢> // // Date : 15:01 2023/5/5 -func (str String) ToAnySlice() AnySliceResult { +func (str String) ToAnySlice(splitCharList ...string) AnySliceResult { result := AnySliceResult{ Value: []interface{}{}, Err: nil, } - result.Err = serialize.JSON.UnmarshalWithNumber([]byte(str), &result.Value) + if len(splitCharList) == 0 { + result.Err = serialize.JSON.UnmarshalWithNumber([]byte(str), &result.Value) + return result + } + + valArr := strings.Split(str.Value(), splitCharList[0]) + valList := make([]interface{}, 0) + for _, item := range valArr { + v := String(item) + if res := v.ToInt64(); nil == res.Err { + valList = append(valList, res.Value) + } else if res := v.ToUint64(); nil == res.Err { + valList = append(valList, res.Value) + } else if res := v.ToFloat64(); nil == res.Err { + valList = append(valList, res.Value) + } else if res := v.ToBool(); nil == res.Err { + valList = append(valList, res.Value) + } else { + valList = append(valList, item) + } + } + result.Value = valList return result } diff --git a/string_test.go b/string_test.go index e6d43b4..76f1f98 100644 --- a/string_test.go +++ b/string_test.go @@ -23,3 +23,9 @@ func TestString_ToFloat32(t *testing.T) { fmt.Println(str.ToInt()) fmt.Println(str.ToUint()) } + +func TestString_ToAnySlice(t *testing.T) { + str := "1,2,3" + r := String(str).ToAnySlice(",") + fmt.Println(r) +}