How can I convert custom type to interface{} and then to base type (ex. uint8)?
I can't use direct cast like uint16(val.(Year)) because I may not know all custom types, but I can determinate base types (uint8, uint32,...) in runtime
There are many custom types (usually used as enums) based on numeric:
ex:
type Year uint16
type Day uint8
type Month uint8
and so on...
The question is about type casting from interface{} to base types:
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)))
}
You can accomplish this by using the
reflectpackage:Depending on your situation, you may want to return
(uint16, error), instead of returning the empty value.https://play.golang.org/p/sYm1jTCMIf