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)
	}
}
相关推荐
Y4090013 分钟前
C语言转Java语言,相同与相异之处
java·c语言·开发语言·笔记
松哥_ai自动化2 小时前
从抓包GitHub Copilot认证请求,认识OAuth 2.0技术
github·copilot
古月-一个C++方向的小白5 小时前
C++11之lambda表达式与包装器
开发语言·c++
沐知全栈开发6 小时前
Eclipse 生成 jar 包
开发语言
杭州杭州杭州7 小时前
Python笔记
开发语言·笔记·python
tanyongxi667 小时前
C++ AVL树实现详解:平衡二叉搜索树的原理与代码实现
开发语言·c++
阿葱(聪)8 小时前
java 在k8s中的部署流程
java·开发语言·docker·kubernetes
浮生带你学Java9 小时前
2025Java面试题及答案整理( 2025年 7 月最新版,持续更新)
java·开发语言·数据库·面试·职场和发展
斯是 陋室9 小时前
在CentOS7.9服务器上安装.NET 8.0 SDK
运维·服务器·开发语言·c++·c#·云计算·.net
李长渊哦10 小时前
深入理解Java中的Map.Entry接口
java·开发语言