Go CastGo 類型轉(zhuǎn)換庫
Cast是一個(gè)庫,以一致和簡單的方式在不同的Go類型之間轉(zhuǎn)換。
Cast提供了簡單的函數(shù),可以輕松地將數(shù)字轉(zhuǎn)換為字符串,將接口轉(zhuǎn)換為bool類型等等。當(dāng)一個(gè)明顯的轉(zhuǎn)換是可能的時(shí),Cast會智能地執(zhí)行這一操作。它不會試圖猜測你的意思,例如,你只能將一個(gè)字符串轉(zhuǎn)換為int的字符串表示形式,例如“8”。Cast是為Hugo開發(fā)的,Hugo是一個(gè)使用YAML、TOML或JSON作為元數(shù)據(jù)的網(wǎng)站引擎。
為什么使用Cast?
在Go中處理動態(tài)數(shù)據(jù)時(shí),通常需要將數(shù)據(jù)從一種類型轉(zhuǎn)換為另一種類型。強(qiáng)制轉(zhuǎn)換不僅僅是使用類型斷言(盡管它在可能的情況下使用類型斷言),它提供了一個(gè)非常直接和方便的庫。
如果您正在使用接口來處理諸如動態(tài)內(nèi)容之類的事情,那么您將需要一種簡單的方法來將接口轉(zhuǎn)換為給定類型。
如果您從YAML、TOML或JSON或其他缺乏完整類型的格式中獲取數(shù)據(jù),那么Cast就是適合您的庫。
使用方式
強(qiáng)制轉(zhuǎn)換提供了一些To_ 的方法。這些方法將始終返回所需的類型。如果提供的輸入不能轉(zhuǎn)換為該類型,則返回該類型的0或nil值。
Cast也提供了 To_E相同的方法。這些方法返回與To_方法相同的結(jié)果,外加一個(gè)額外的錯誤,告訴您是否成功轉(zhuǎn)換。使用這些方法,您可以分辨輸入匹配零值時(shí)的不同,以及轉(zhuǎn)換失敗時(shí)返回零值時(shí)的不同。
案例
下面的例子僅僅是現(xiàn)有例子的一個(gè)例子。請查看完整的代碼集。
Example ‘ToString’:
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"
Example ‘ToInt’:
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
main函數(shù)
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
