Skip to content

spf13/cast

倉庫: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

Golang學習網由www.golangdev.cn整理維護