From 56fc12c660cddbee9a9312cf7967ab123830b31e Mon Sep 17 00:00:00 2001 From: dudaodong Date: Mon, 3 Jan 2022 15:15:22 +0800 Subject: [PATCH] refactor: reduce gocyclo of ToString func --- convertor/convertor.go | 48 +++++++++++++++---------------------- convertor/convertor_test.go | 9 +++++-- 2 files changed, 26 insertions(+), 31 deletions(-) diff --git a/convertor/convertor.go b/convertor/convertor.go index 0569729..ead1405 100644 --- a/convertor/convertor.go +++ b/convertor/convertor.go @@ -45,44 +45,34 @@ func ToChar(s string) []string { // ToString convert value to string func ToString(value interface{}) string { - var res string + res := "" if value == nil { return res } - switch v := value.(type) { - case float64: - res = strconv.FormatFloat(v, 'f', -1, 64) - case float32: - res = strconv.FormatFloat(float64(v), 'f', -1, 64) - case int: - res = strconv.Itoa(v) - case uint: - res = strconv.Itoa(int(v)) - case int8: - res = strconv.Itoa(int(v)) - case uint8: - res = strconv.Itoa(int(v)) - case int16: - res = strconv.Itoa(int(v)) - case uint16: - res = strconv.Itoa(int(v)) - case int32: - res = strconv.Itoa(int(v)) - case uint32: - res = strconv.Itoa(int(v)) - case int64: - res = strconv.FormatInt(v, 10) - case uint64: - res = strconv.FormatUint(v, 10) + + v := reflect.ValueOf(value) + + switch value.(type) { + case float32, float64: + res = strconv.FormatFloat(v.Float(), 'f', -1, 64) + return res + case int, int8, int16, int32, int64: + res = strconv.FormatInt(v.Int(), 10) + return res + case uint, uint8, uint16, uint32, uint64: + res = strconv.FormatUint(v.Uint(), 10) + return res case string: - res = value.(string) + res = v.String() + return res case []byte: - res = string(value.([]byte)) + res = string(v.Bytes()) + return res default: newValue, _ := json.Marshal(value) res = string(newValue) + return res } - return res } // ToJson convert value to a valid json string diff --git a/convertor/convertor_test.go b/convertor/convertor_test.go index 5066751..9bb2b73 100644 --- a/convertor/convertor_test.go +++ b/convertor/convertor_test.go @@ -108,14 +108,19 @@ func TestToString(t *testing.T) { aStruct := TestStruct{Name: "TestStruct"} cases := []interface{}{ + "", nil, int(0), int8(1), int16(-1), int32(123), int64(123), uint(123), uint8(123), uint16(123), uint32(123), uint64(123), float64(12.3), float32(12.3), true, false, []int{1, 2, 3}, aMap, aStruct, []byte{104, 101, 108, 108, 111}} - expected := []string{"0", "1", "-1", "123", "123", "123", "123", "123", - "123", "123", "12.3", "12.300000190734863", "true", "false", + expected := []string{ + "", "", + "0", "1", "-1", + "123", "123", "123", "123", "123", "123", "123", + "12.3", "12.300000190734863", + "true", "false", "[1,2,3]", "{\"a\":1,\"b\":2,\"c\":3}", "{\"Name\":\"TestStruct\"}", "hello"} for i := 0; i < len(cases); i++ {