淺析golang?github.com/spf13/cast?庫識別不了自定義數(shù)據(jù)類型
以下代碼運行不會是10,而是返回 0
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 這種,返回帶錯誤的函數(shù)
// 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) } }
到此這篇關(guān)于golang github.com/spf13/cast 庫識別不了自定義數(shù)據(jù)類型的文章就介紹到這了,更多相關(guān)golang github.com/spf13/cast 庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Go?Excelize?API源碼解析GetSheetFormatPr使用示例
這篇文章主要為大家介紹了Go?Excelize?API源碼解析GetSheetFormatPr使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08golang利用unsafe操作未導(dǎo)出變量-Pointer使用詳解
這篇文章主要給大家介紹了關(guān)于golang利用unsafe操作未導(dǎo)出變量-Pointer使用的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-08-08Go語言之重要數(shù)組類型切片(slice)make,append函數(shù)解讀
這篇文章主要介紹了Go語言之重要數(shù)組類型切片(slice)make,append函數(shù)用法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09Golang?中判斷兩個結(jié)構(gòu)體相等的方法
這篇文章主要介紹了Golang?中如何判斷兩個結(jié)構(gòu)體相等,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08使用gopkg.in/yaml.v3?解析YAML數(shù)據(jù)詳解
這篇文章主要為大家介紹了使用gopkg.in/yaml.v3?解析YAML數(shù)據(jù)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09