加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang:将类型转换为基本类型

发布时间:2020-12-16 19:29:07 所属栏目:大数据 来源:网络整理
导读:如何将自定义类型转换为接口{},然后转换为基本类型(例如uint8)? 我不能使用像uint16(val.(Year))这样的直接转换,因为我可能不知道所有的自定义类型,但是我可以在运行时确定基本类型(uint8,uint32,…) 基于数字,有很多自定义类型(通常用作枚举): 例如: typ
如何将自定义类型转换为接口{},然后转换为基本类型(例如uint8)?

我不能使用像uint16(val.(Year))这样的直接转换,因为我可能不知道所有的自定义类型,但是我可以在运行时确定基本类型(uint8,uint32,…)

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

例如:

type Year  uint16
type Day   uint8
type Month uint8

等等…

问题是关于从界面{}到基本类型的类型转换:

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

您可以使用 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,错误),而不是返回空值.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读