如何将自定义类型转换interface{}
为基本类型(例如uint8
)?
我不能用直接铸造的喜欢uint16(val.(Year))
,因为我可能不知道所有的自定义类型,但是我能确定的基本类型(uint8
,uint32
,...)在运行时
基于数字的自定义类型很多(通常用作枚举):
例如:
type Year uint16
type Day uint8
type Month uint8
等等...
问题是关于从类型转换interface{}
为基本类型的问题:
package main
import "fmt"
type Year uint16
// ....
//Many others custom types based on uint8
func AsUint16(val interface{}) uint16 {
return val.(uint16) //FAIL: cannot convert val (type interface {}) to type uint16: need type assertion
}
func AsUint16_2(val interface{}) uint16 {
return uint16(val) //FAIL: cannot convert val (type interface {}) to type uint16: need type assertion
}
func main() {
fmt.Println(AsUint16_2(Year(2015)))
}
您可以使用以下reflect
软件包来完成此操作:
package main
import "fmt"
import "reflect"
type Year uint16
func AsUint16(val interface{}) uint16 {
ref := reflect.ValueOf(val)
if ref.Kind() != reflect.Uint16 {
return 0
}
return uint16(ref.Uint())
}
func main() {
fmt.Println(AsUint16(Year(2015)))
}
根据您的情况,您可能需要返回(uint16, error)
,而不是返回空值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句