Skip to content

Commit 596ea3c

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

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

tea/utils/utils.go

Lines changed: 39 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,39 @@ 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 nil
133+
}
134+
// 使用 reflect 获取值
135+
v := reflect.ValueOf(obj)
136+
137+
// 如果是指针,获取其指向的值
138+
if v.Kind() == reflect.Ptr {
139+
if v.IsNil() {
140+
return nil
141+
}
142+
// 获取指针指向的值
143+
v = v.Elem()
144+
}
145+
146+
var res string
147+
// 根据类型转换为字符串
148+
switch v.Kind() {
149+
case reflect.String:
150+
res = v.String()
151+
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
152+
res = strconv.FormatInt(v.Int(), 10)
153+
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
154+
res = strconv.FormatUint(v.Uint(), 10)
155+
case reflect.Float32, reflect.Float64:
156+
res = strconv.FormatFloat(v.Float(), 'f', -1, 64)
157+
case reflect.Bool:
158+
res = strconv.FormatBool(v.Bool())
159+
default:
160+
res = fmt.Sprintf("%v", obj)
161+
}
162+
return &res
163+
}

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)