我在 Go (1.18.1) 中撰寫了一個簡單的函式,它將any(ak interface{}) 型別作為輸入,并將值作為字串回傳,如果是nil指標,函式回傳"nil"; 如果不支持該型別,則函式回傳"?"
// small helper funcion which is usefull when printing (pointer) values
func ToString(T any) string {
switch v := T.(type) {
case string:
return v
case *string:
if v == nil {
return "nil"
} else {
return *v
}
case int:
return strconv.FormatInt(int64(v), 10)
case int8:
return strconv.FormatInt(int64(v), 10)
case int16:
return strconv.FormatInt(int64(v), 10)
case int32:
return strconv.FormatInt(int64(v), 10)
case int64:
return strconv.FormatInt(v, 10)
case float32:
return fmt.Sprintf("%f", v)
case float64:
return fmt.Sprintf("%f", v)
case *int:
if v == nil {
return "nil"
}
return strconv.FormatInt(int64(*v), 10)
case *int8:
if v == nil {
return "nil"
}
return strconv.FormatInt(int64(*v), 10)
case *int16:
if v == nil {
return "nil"
}
return strconv.FormatInt(int64(*v), 10)
case *int32:
if v == nil {
return "nil"
}
return strconv.FormatInt(int64(*v), 10)
case *int64:
if v == nil {
return "nil"
}
return strconv.FormatInt(*v, 10)
case *float32:
if v == nil {
return "nil"
}
return fmt.Sprintf("%f", *v)
case *float64:
if v == nil {
return "nil"
}
return fmt.Sprintf("%f", *v)
case *bool:
if v == nil {
return "nil"
}
case bool:
if v == true {
return "true"
}
return "false"
}
return "?"
}
這完美地完成了它的作業,但是看看實際的演算法,我對代碼重復的數量感到惱火,不幸的是 afallthrough在型別切換陳述句中不起作用(請參閱Why is not fallthrough allowed in a type switch?)。
有沒有更有效的方法(即代碼重復更少)來做與上述ToString(T any)功能相同的事情?
uj5u.com熱心網友回復:
帶有反射的更短代碼:
func ToString(x any) string {
v := reflect.ValueOf(x)
if v.Kind() == reflect.Ptr {
if v.IsZero() {
return "nil"
}
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, v.Type().Bits())
case reflect.Bool:
return strconv.FormatBool(v.Bool())
default:
return "?"
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/474692.html
標籤:去
