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)
	}
}
相关推荐
时艰.4 小时前
java性能调优 — 高并发缓存一致性
java·开发语言·缓存
MSTcheng.5 小时前
【C++】C++智能指针
开发语言·c++·智能指针
无小道5 小时前
Qt——网络编程
开发语言·qt
wazmlp0018873695 小时前
第五次python作业
服务器·开发语言·python
云深处@5 小时前
【C++11】部分特性
开发语言·c++
尘缘浮梦5 小时前
websockets简单例子1
开发语言·python
jxy99985 小时前
mac mini 安装java JDK 17
java·开发语言·macos
独望漫天星辰5 小时前
C++ 树结构进阶:从工程化实现到 STL 底层与性能优化
开发语言·c++
HellowAmy5 小时前
我的C++规范 - 鸡蛋工厂
开发语言·c++·代码规范
叫我一声阿雷吧5 小时前
深入理解JavaScript作用域和闭包,解决变量访问问题
开发语言·javascript·ecmascript