【发布时间】:2017-07-22 16:17:59
【问题描述】:
如何将自定义类型转换为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)))
}
【问题讨论】:
-
请注意,
val.(unit16)和uint16(val)都不是“强制转换”:第一个是“类型断言”,第二个是“类型转换”。
标签: go