Skip to content

Commit 9d5dc69

Browse files
committed
Feature: 添加ToString方法及测试
1 parent 81345ae commit 9d5dc69

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

tea/utils/utils.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,11 @@ import (
44
"crypto/hmac"
55
"crypto/sha1"
66
"encoding/base64"
7+
"fmt"
78
"net/url"
9+
"reflect"
810
"sort"
11+
"strconv"
912
"strings"
1013
"time"
1114
)
@@ -122,3 +125,37 @@ func GetSignature(strToSign *string, accessKeyId *string, accessKeySecret *strin
122125
res := "ODPS " + *accessKeyId + ":" + signature
123126
return &res
124127
}
128+
129+
// ToString 转换为字符串,能够兼容指针类型与非指针类型
130+
func ToString(obj interface{}) string {
131+
if obj == nil {
132+
return ""
133+
}
134+
// 使用 reflect 获取值
135+
v := reflect.ValueOf(obj)
136+
137+
// 如果是指针,获取其指向的值
138+
if v.Kind() == reflect.Ptr {
139+
if v.IsNil() {
140+
return ""
141+
}
142+
// 获取指针指向的值
143+
v = v.Elem()
144+
}
145+
146+
// 根据类型转换为字符串
147+
switch v.Kind() {
148+
case reflect.String:
149+
return v.String()
150+
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
151+
return strconv.FormatInt(v.Int(), 10)
152+
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
153+
return strconv.FormatUint(v.Uint(), 10)
154+
case reflect.Float32, reflect.Float64:
155+
return strconv.FormatFloat(v.Float(), 'f', -1, 64)
156+
case reflect.Bool:
157+
return strconv.FormatBool(v.Bool())
158+
default:
159+
return fmt.Sprintf("%v", obj)
160+
}
161+
}

tea/utils/utils_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package utils
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
)
7+
8+
func TestToString(t *testing.T) {
9+
value := "hello"
10+
var ptr *string
11+
ptr = &value
12+
13+
t.Log(fmt.Sprintf("%v", ptr)) // 0x000
14+
t.Log(ToString(ptr)) // hello
15+
t.Log(ToString(value)) // hello
16+
}

0 commit comments

Comments
 (0)