From d87dbffa445d6718925785d9ecb8f029f57f64ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BC=8E=E6=98=95?= Date: Mon, 13 Jan 2025 18:57:33 +0800 Subject: [PATCH] =?UTF-8?q?feat(tea):=20=E6=B7=BB=E5=8A=A0ToString?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E5=8F=8A=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tea/utils/utils.go | 37 +++++++++++++++++++++++++++++++++++++ tea/utils/utils_test.go | 16 ++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 tea/utils/utils_test.go diff --git a/tea/utils/utils.go b/tea/utils/utils.go index a301d81..c59c968 100644 --- a/tea/utils/utils.go +++ b/tea/utils/utils.go @@ -4,8 +4,11 @@ import ( "crypto/hmac" "crypto/sha1" "encoding/base64" + "fmt" "net/url" + "reflect" "sort" + "strconv" "strings" "time" ) @@ -122,3 +125,37 @@ func GetSignature(strToSign *string, accessKeyId *string, accessKeySecret *strin res := "ODPS " + *accessKeyId + ":" + signature return &res } + +// ToString 转换为字符串,能够兼容指针类型与非指针类型 +func ToString(obj interface{}) string { + if obj == nil { + return "" + } + // 使用 reflect 获取值 + v := reflect.ValueOf(obj) + + // 如果是指针,获取其指向的值 + if v.Kind() == reflect.Ptr { + if v.IsNil() { + return "" + } + // 获取指针指向的值 + v = v.Elem() + } + + // 根据类型转换为字符串 + switch v.Kind() { + case reflect.String: + return v.String() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return strconv.FormatInt(v.Int(), 10) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return strconv.FormatUint(v.Uint(), 10) + case reflect.Float32, reflect.Float64: + return strconv.FormatFloat(v.Float(), 'f', -1, 64) + case reflect.Bool: + return strconv.FormatBool(v.Bool()) + default: + return fmt.Sprintf("%v", obj) + } +} diff --git a/tea/utils/utils_test.go b/tea/utils/utils_test.go new file mode 100644 index 0000000..372c9f7 --- /dev/null +++ b/tea/utils/utils_test.go @@ -0,0 +1,16 @@ +package utils + +import ( + "fmt" + "testing" +) + +func TestToString(t *testing.T) { + value := "hello" + var ptr *string + ptr = &value + + t.Log(fmt.Sprintf("%v", ptr)) // 0x000 + t.Log(ToString(ptr)) // hello + t.Log(ToString(value)) // hello +}