淺析golang?github.com/spf13/cast?庫識(shí)別不了自定義數(shù)據(jù)類型
以下代碼運(yùn)行不會(huì)是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()直接屏蔽了錯(cuò)誤,可以使用 ToInt64E 這種,返回帶錯(cuò)誤的函數(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í)別不了自定義數(shù)據(jù)類型的文章就介紹到這了,更多相關(guān)golang github.com/spf13/cast 庫內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
golang 實(shí)現(xiàn)比特幣內(nèi)核之處理橢圓曲線中的天文數(shù)字
比特幣密碼學(xué)中涉及到的大數(shù)運(yùn)算超出常規(guī)整數(shù)范圍,需使用golang的big包進(jìn)行處理,通過使用big.Int類型,能有效避免整數(shù)溢出,并保持邏輯正確性,測(cè)試展示了在不同質(zhì)數(shù)模下的運(yùn)算結(jié)果,驗(yàn)證了邏輯的準(zhǔn)確性,此外,探討了費(fèi)馬小定理在有限字段除法運(yùn)算中的應(yīng)用2024-11-11
Go數(shù)據(jù)結(jié)構(gòu)之映射map方式
這篇文章主要介紹了Go數(shù)據(jù)結(jié)構(gòu)之映射map方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-06-06
淺談Golang中創(chuàng)建一個(gè)簡(jiǎn)單的服務(wù)器的方法
這篇文章主要介紹了淺談Golang中創(chuàng)建一個(gè)簡(jiǎn)單的服務(wù)器的方法,golang中的net/http包對(duì)網(wǎng)絡(luò)的支持非常好,這樣會(huì)讓我們比較容易的建立起一個(gè)相對(duì)簡(jiǎn)單的服務(wù)器,有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06
GoLang中的timer定時(shí)器實(shí)現(xiàn)原理分析
Timer中對(duì)外暴露的只有一個(gè)channel,這個(gè) channel也是定時(shí)器的核心。當(dāng)計(jì)時(shí)結(jié)束時(shí),Timer會(huì)發(fā)送值到channel中,外部環(huán)境在這個(gè) channel 收到值的時(shí)候,就代表計(jì)時(shí)器超時(shí)了,可與select搭配執(zhí)行一些超時(shí)邏輯2023-02-02

