如何将自定义类型转换为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)))
}
http://play.golang.org/p/cyAnzQ90At
请注意,既不'VAL(unit16)''也不UINT16(VAL)'是一个 “转换”:第一个是 “类型的断言”,第二个和 “类型转换”。 – Volker