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)
	}
}
相关推荐
jinanwuhuaguo6 分钟前
(第三十三篇)五月的文明奠基:OpenClaw 2026.5.2版本的文明级解读
android·java·开发语言·人工智能·github·拓扑学·openclaw
DogDaoDao1 小时前
【GitHub】andrej-karpathy-skills:让 AI 编程助手告别三大通病
人工智能·深度学习·程序员·大模型·github·ai编程·andrej-karpathy
有一个好名字1 小时前
工具即双手 —— 从 Bash 到 Tool Dispatch Map
开发语言·chrome·bash
Lyyaoo.1 小时前
优惠券秒杀业务分析
java·开发语言
DevilSeagull2 小时前
MySQL(2) 客户端工具和建库
开发语言·数据库·后端·mysql·服务
MATLAB代码顾问2 小时前
改进遗传算法(IGA)求解作业车间调度问题(JSSP)——附MATLAB代码
开发语言·matlab
syker2 小时前
AIFerric深度学习框架:自研全栈AI基础设施的技术全景
开发语言·c++
HSunR3 小时前
dify 搭建ai作业批改流
开发语言·前端·javascript
代码不加糖3 小时前
2026 跨境电商独立站实战:从 0 到 1 搭建高转化 SaaS 商城(附源码)
开发语言·前端·javascript
时空系3 小时前
第9篇:成员功能——为结构体添加能力 Rust中文编程
开发语言·网络·rust