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)
	}
}
相关推荐
凯瑟琳.奥古斯特7 小时前
动态调优IoU提升OCR文本合并精度
开发语言·python·算法
陌陌龙7 小时前
【紧急预警!PHP 核弹级漏洞 php2shell】
开发语言·php
白露与泡影7 小时前
一线 Java 后端面试八股(2026 更新版,含完整答案)
java·开发语言·面试
企业解惑小能手-域智盾系统7 小时前
内网监控软件策略不生效、日志缺失?一套从现象到根因的排查框架
开发语言·php·域智盾
1024奇点7 小时前
【仓颉语言入门 · 第二篇 第 10 课】
开发语言·数据库·ide·mysql·开源
布莱克6057 小时前
A* 算法详解:从原理到实现
开发语言·c++·算法
多弗朗皮卡丘7 小时前
C++ 智能指针
开发语言·c++·c++11·智能指针
数据狐(Datafox)7 小时前
一文读懂京东商品详情API:返回字段解读与 JSON 样例
java·开发语言·数据库·windows·json
CoovallyAIHub7 小时前
Anthropic 昨晚发布 Claude Duet:AI 第一次主动找你干活
github·agent·设计
小成202303202657 小时前
C++~02运算符重载
开发语言·c++