I was wondering if I could implement a less verbose version of this function. It would be great if it had better performance.
func AnyIntToInt(x interface{}) (int, error) {
switch val := x.(type) {
case int8:
return int(val), nil
case int16:
return int(val), nil
case int32:
return int(val), nil
case int64:
return int(val), nil
case uint8:
return int(val), nil
case uint16:
return int(val), nil
case uint32:
return int(val), nil
case uint64:
return int(val), nil
}
return 0, ErrNotInteger
}
I have been trying with this one, however it yields unexpected results.
func AnyIntToInt(x interface{}) (int, error) {
return *(*int)(unsafe.Pointer(&x))
}
CodePudding user response:
The code in the question is the way to go, but you can reduce lines of code using the reflect package:
func AnyIntToInt(x interface{}) (int, error) {
v := reflect.ValueOf(x)
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return int(v.Int()), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return int(v.Uint()), nil
}
return 0, ErrNotInteger
}