(编辑:jimmy 日期: 2025/10/24 浏览:2)
https://github.com/spf13/cast
Cast是一个库,以一致和简单的方式在不同的go类型之间转换。
Cast提供了简单的函数,可以轻松地将数字转换为字符串,将接口转换为bool类型等等。当一个明显的转换是可能的时,Cast会智能地执行这一操作。它不会试图猜测你的意思,例如,你只能将一个字符串转换为int的字符串表示形式,例如“8”。Cast是为Hugo开发的,Hugo是一个使用YAML、TOML或JSON作为元数据的网站引擎。
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"
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
package main
import (
"fmt"
"reflect"
"github.com/spf13/cast"
)
func main() {
var foo interface{} = "one more time"
box := cast.ToString(foo)
fmt.Println(box)
box = cast.ToString("3.12021")
fmt.Println(box)
cvIntBox := cast.ToInt(8)
fmt.Println(cvIntBox, reflect.TypeOf(cvIntBox))
cvFloatBox := cast.ToFloat32(8.31)
fmt.Println(cvFloatBox, reflect.TypeOf(cvFloatBox))
cvBoolBox := cast.ToBool(true)
fmt.Println(cvBoolBox, reflect.TypeOf(cvBoolBox))
}
输出
one more time
3.12021
8 int
8.31 float32
true bool
以上就是golang类型转换组件Cast的使用详解的详细内容,更多关于golang类型转换组件Cast的资料请关注其它相关文章!