golang interface{}類型轉(zhuǎn)換的實(shí)現(xiàn)示例
Golang中存在4種類型轉(zhuǎn)換,分別是:斷言、顯式、隱式、強(qiáng)制。下面我將一一介紹每種轉(zhuǎn)換使用場景和方法
遇到interface{}類型轉(zhuǎn)換成float32 或者 float64類型進(jìn)行存儲(chǔ),go中對變量類型轉(zhuǎn)換有比較嚴(yán)格要求。
type斷言
type斷言配合switch 對每種類型的變量進(jìn)行轉(zhuǎn)換
func TpyeTransfer(value interface{}) (typ int, val interface{}) { switch value.(type) { case int: return 6, float32(value.(int)) case bool: return 3, value.(bool) case int8: return 6, float32(value.(int8)) case int16: return 6, float32(value.(int16)) case int32: return 6, float32(value.(int32)) case uint8: return 6, float32(value.(uint8)) case uint16: return 6, float32(value.(uint16)) case uint32: return 6, float32(value.(uint32)) case float32: return 6, float32(value.(float32)) case string: fmt.Printf("data type string is %T \n", value) return 0, value case int64: return 10, float64(value.(int64)) case float64: return 10, float64(value.(float64)) case uint64: return 10, float64(value.(uint64)) default: fmt.Printf("data type is:%T \n", value) return 0, value }
這樣轉(zhuǎn)換有兩個(gè)問題
1.對切片無法判斷,切片有多個(gè)變量數(shù)值需要逐個(gè)處理
2.不能對多個(gè)類型的變量進(jìn)行統(tǒng)一轉(zhuǎn)換
reflect.TypeOf
利用reflect包進(jìn)行處理,reflect包不能識(shí)別time.Time等其他包引入的結(jié)構(gòu)體變量,需要和type斷言組合使用
func typereflect(value interface{}) (typ int, val interface{}) { res := reflect.ValueOf(value) switch res.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32: return 6, float32(res.Int()) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32: return 6, float32(res.Uint()) case reflect.Float32: return 6, float32(res.Float()) case reflect.Int64: return 10, float64(res.Int()) case reflect.Uint64: return 10, float64(res.Uint()) case reflect.Float64: return 10, res.Float() case reflect.Bool: return 3, res.Bool() default: fmt.Printf("ohter type is:%T \n", value) switch value.(type) { case time.Time: time := value.(time.Time) fmt.Println("time is ", time.Unix()) } return 0, val } }
如上兩種方法感覺都不完美,在go中還沒有趙傲比較完美的處理interface{}變量的方法,有了解更多處理方法的大神一起交流一下
到此這篇關(guān)于golang interface{}類型轉(zhuǎn)換的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)golang interface{}類型轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
golang json.Marshal 特殊html字符被轉(zhuǎn)義的解決方法
今天小編就為大家分享一篇golang json.Marshal 特殊html字符被轉(zhuǎn)義的解決方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08go語言開發(fā)環(huán)境安裝及第一個(gè)go程序(推薦)
這篇文章主要介紹了go語言開發(fā)環(huán)境安裝及第一個(gè)go程序,這篇通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02Go語言實(shí)現(xiàn)將中文轉(zhuǎn)化為拼音功能
這篇文章主要為大家詳細(xì)介紹了Go語言中如何實(shí)現(xiàn)將中文轉(zhuǎn)化為拼音功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-01-01聊聊go xorm生成mysql的結(jié)構(gòu)體問題
這篇文章主要介紹了go xorm生成mysql的結(jié)構(gòu)體問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2022-03-03