键入自定义类型到基类型

Ale*_*Bar 19 go

如何将自定义类型转换interface{}为基本类型(例如uint8)?

我不能用直接铸造的喜欢uint16(val.(Year)),因为我可能不知道所有的自定义类型,但是我能确定的基本类型(uint8,uint32在运行时,...)


有许多基于数字的自定义类型(通常用作枚举):

例如:

type Year  uint16
type Day   uint8
type Month uint8
Run Code Online (Sandbox Code Playgroud)

等等...

问题是从类型转换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)))
}
Run Code Online (Sandbox Code Playgroud)

http://play.golang.org/p/cyAnzQ90At

Tim*_*per 13

您可以使用该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)))
}
Run Code Online (Sandbox Code Playgroud)

根据您的具体情况,您可能希望返回(uint16, error),而不是返回空值.

https://play.golang.org/p/sYm1jTCMIf


Ric*_*777 7

你为什么包括Year在问题中?您是希望将任意事物转换为 Years,还是将 Years 转换为 uint16s?

如果我假设您的意思是后一种情况,那么最好使用一种方法

func (y Year) AsUint16() uint16 { 
    return uint16(y)
}
Run Code Online (Sandbox Code Playgroud)

这不需要任何类型断言或反射。

https://play.golang.org/p/9wCQJe46PU