golang github.com/spf13/cast 库识别不了 自定义数据类型

以下代码运行不会是10,而是返回 0

Go 复制代码
package main

import (
	"fmt"
	"github.com/spf13/cast"
)

type UserNum int32

func main() {
	var uNum UserNum
	uNum = 10
	uNumint64 := cast.ToInt64(uNum)
	uNumint64E, err := cast.ToInt64E(uNum)
	fmt.Println(uNumint64)
	fmt.Println(uNumint64E, err)
}

看一下源码,ToInt64()直接屏蔽了错误,可以使用 ToInt64E 这种,返回带错误的函数

Go 复制代码
// ToInt64 casts an interface to an int64 type.
func ToInt64(i interface{}) int64 {
	v, _ := ToInt64E(i)
	return v
}

// ToInt64E casts an interface to an int64 type.
func ToInt64E(i interface{}) (int64, error) {
	i = indirect(i)

	intv, ok := toInt(i)
	if ok {
		return int64(intv), nil
	}

	switch s := i.(type) {
	case int64:
		return s, nil
	case int32:
		return int64(s), nil
	case int16:
		return int64(s), nil
	case int8:
		return int64(s), nil
	case uint:
		return int64(s), nil
	case uint64:
		return int64(s), nil
	case uint32:
		return int64(s), nil
	case uint16:
		return int64(s), nil
	case uint8:
		return int64(s), nil
	case float64:
		return int64(s), nil
	case float32:
		return int64(s), nil
	case string:
		v, err := strconv.ParseInt(trimZeroDecimal(s), 0, 0)
		if err == nil {
			return v, nil
		}
		return 0, fmt.Errorf("unable to cast %#v of type %T to int64", i, i)
	case json.Number:
		return ToInt64E(string(s))
	case bool:
		if s {
			return 1, nil
		}
		return 0, nil
	case nil:
		return 0, nil
	default:
		return 0, fmt.Errorf("unable to cast %#v of type %T to int64", i, i)
	}
}
相关推荐
吕司26 分钟前
Qt的信号与槽
开发语言·qt
bjxiaxueliang1 小时前
一文掌握C/C++命名规范:风格、规则与实践详解
c语言·开发语言·c++
玄〤1 小时前
Java 大数据量输入输出优化方案详解:从 Scanner 到手写快读(含漫画解析)
java·开发语言·笔记·算法
NBhhbYyOljP2 小时前
LabVIEW与西门子PLC S7200SMART 12001500 300 400
golang
一起养小猫2 小时前
Flutter for OpenHarmony 实战:番茄钟应用完整开发指南
开发语言·jvm·数据库·flutter·信息可视化·harmonyos
独自破碎E2 小时前
总持续时间可被 60 整除的歌曲
java·开发语言
senijusene2 小时前
数据结构与算法:队列与树形结构详细总结
开发语言·数据结构·算法
好好沉淀2 小时前
Elasticsearch 中获取返回匹配记录总数
开发语言·elasticsearch
2301_765703142 小时前
C++与自动驾驶系统
开发语言·c++·算法
MediaTea2 小时前
<span class=“js_title_inner“>Python:实例对象</span>
开发语言·前端·javascript·python·ecmascript