我想知道我是否可以實(shí)現(xiàn)這個(gè)函數(shù)的不那么冗長(zhǎng)的版本。如果它有更好的性能,那就太好了。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}我一直在嘗試這個(gè),但是它產(chǎn)生了意想不到的結(jié)果。func AnyIntToInt(x interface{}) (int, error) { return *(*int)(unsafe.Pointer(&x))}
1 回答

汪汪一只貓
TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個(gè)贊
問(wèn)題中的代碼是要走的路,但是您可以使用反射包減少代碼行:
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
- 1 回答
- 0 關(guān)注
- 123 瀏覽
添加回答
舉報(bào)
0/150
提交
取消