Skip to content

Commit

Permalink
Feature: 添加ToString方法及测试
Browse files Browse the repository at this point in the history
  • Loading branch information
dingxin-tech committed Jan 13, 2025
1 parent 81345ae commit 9d5dc69
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
37 changes: 37 additions & 0 deletions tea/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@ import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"net/url"
"reflect"
"sort"
"strconv"
"strings"
"time"
)
Expand Down Expand Up @@ -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)
}
}
16 changes: 16 additions & 0 deletions tea/utils/utils_test.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit 9d5dc69

Please sign in to comment.