英文:
Is there a way to implement this integer casting function with unsafe Pointer in golang?
问题
我在想是否可以实现一个更简洁的函数版本,并且性能更好会很棒。
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
}
我尝试了下面这个版本,但是它产生了意外的结果。
func AnyIntToInt(x interface{}) (int, error) {
return *(*int)(unsafe.Pointer(&x))
}
英文:
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))
}
答案1
得分: 1
问题中的代码是正确的方法,但是你可以使用reflect包来减少代码行数:
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
}
https://go.dev/play/p/gJ4ASo7AeyN
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论