1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-09 15:12:26 +08:00

refactor: code improvement, ToString, Contain, Compact

This commit is contained in:
dudaodong
2022-12-01 11:38:14 +08:00
parent 6f458e4367
commit a16de97d1d
3 changed files with 53 additions and 36 deletions

View File

@@ -90,34 +90,50 @@ func ToChannel[T any](array []T) <-chan T {
}
// ToString convert value to string
// for number, string, []byte, will convert to string
// for other type (slice, map, array, struct) will call json.Marshal
func ToString(value any) string {
result := ""
if value == nil {
return result
return ""
}
v := reflect.ValueOf(value)
switch value.(type) {
case float32, float64:
result = strconv.FormatFloat(v.Float(), 'f', -1, 64)
return result
case int, int8, int16, int32, int64:
result = strconv.FormatInt(v.Int(), 10)
return result
case uint, uint8, uint16, uint32, uint64:
result = strconv.FormatUint(v.Uint(), 10)
return result
case float32:
return strconv.FormatFloat(float64(value.(float32)), 'f', -1, 32)
case float64:
return strconv.FormatFloat(value.(float64), 'f', -1, 64)
case int:
return strconv.FormatInt(int64(value.(int)), 10)
case int8:
return strconv.FormatInt(int64(value.(int8)), 10)
case int16:
return strconv.FormatInt(int64(value.(int16)), 10)
case int32:
return strconv.FormatInt(int64(value.(int32)), 10)
case int64:
return strconv.FormatInt(value.(int64), 10)
case uint:
return strconv.FormatUint(uint64(value.(uint)), 10)
case uint8:
return strconv.FormatUint(uint64(value.(uint8)), 10)
case uint16:
return strconv.FormatUint(uint64(value.(uint16)), 10)
case uint32:
return strconv.FormatUint(uint64(value.(uint32)), 10)
case uint64:
return strconv.FormatUint(value.(uint64), 10)
case string:
result = v.String()
return result
return value.(string)
case []byte:
result = string(v.Bytes())
return result
return string(value.([]byte))
default:
newValue, _ := json.Marshal(value)
result = string(newValue)
return result
return string(newValue)
// todo: maybe we should't supprt other type convertion
// v := reflect.ValueOf(value)
// log.Panicf("Unsupported data type: %s ", v.String())
// return ""
}
}

View File

@@ -137,9 +137,10 @@ func TestToString(t *testing.T) {
"", "",
"0", "1", "-1",
"123", "123", "123", "123", "123", "123", "123",
"12.3", "12.300000190734863",
"12.3", "12.3",
"true", "false",
"[1,2,3]", "{\"a\":1,\"b\":2,\"c\":3}", "{\"Name\":\"TestStruct\"}", "hello"}
"[1,2,3]", "{\"a\":1,\"b\":2,\"c\":3}", "{\"Name\":\"TestStruct\"}", "hello",
}
for i := 0; i < len(cases); i++ {
actual := ToString(cases[i])