spf13/cast
阅读提示
- 适用版本:Go 1.21+(示例在 Go 1.22 下验证)· 前置知识:语法基础-数据类型 · 阅读时长:约 8 分钟
仓库:spf13/cast: safe and easy casting from one type to another in Go (github.com)
文档:spf13/cast: safe and easy casting from one type to another in Go (github.com)
简介
cast是一个简单的类型转换库,用于将一个类型到另一个类型的快速转换,可以省去很多麻烦的操作。
安装
go get https://github.com/spf13/cast例子
字符串
go
cast.ToString("mayonegg") // "mayonegg"
cast.ToString(8) // "8"
cast.ToString(8.31) // "8.31"
cast.ToString([]byte("one time")) // "one time"
cast.ToString(nil) // ""
var foo interface{} = "one more time"
cast.ToString(foo) // "one more time"整型
go
cast.ToInt(8) // 8
cast.ToInt(8.31) // 8
cast.ToInt("8") // 8
cast.ToInt(true) // 1
cast.ToInt(false) // 0
var eight interface{} = 8
cast.ToInt(eight) // 8
cast.ToInt(nil) // 0完整示例
下面的程序可以直接运行:复制到文件后执行 go run main.go,或粘贴到 Go Playground 运行。
go
package main
import (
"fmt"
"strconv"
)
func toInt(v any) int {
switch x := v.(type) {
case int:
return x
case string:
n, _ := strconv.Atoi(x)
return n
case float64:
return int(x)
default:
return 0
}
}
func main() {
fmt.Println(toInt("42"), toInt(7), toInt(3.9), toInt(nil))
}预期输出:
text
42 7 3 0常见错误与踩坑
- 转换失败会静默返回零值。
cast.ToInt("abc")得到0;当零是合法值时必须自行校验。 - 浮点会截断。
cast.ToInt(3.9)是3;需要四舍五入时要显式处理。 nil会映射为零值。 不能借结果区分"缺失"与零值。- 布尔转整数是 1/0。 方便但也容易在混合数据里产生歧义。
- 时间解析依赖猜测格式。 业务关键场景应显式指定 layout。
更新记录
- 2026-10-14:新增"阅读提示"、完整可运行示例(含预期输出)、常见错误与踩坑清单,以及本更新记录。
