了解學習golang類型斷言
以下由golang教學欄位來介紹golang類型斷言,希望對需要的朋友有幫助!
在php中有一個serialize() 函數可以把陣列序列化成字串進行儲存和傳輸
如果想反序列化這種字串,在php中只需要一個簡單的unserialize() 函數就可以完成了.但是在golang中可就沒有這麼容易了,非得費個九牛二虎之力,寫上不少代碼才行。
這時候只想感嘆一下,php真的是全世界最好的語言啊!
我就在今天的開發中遇到了這麼個問題,需要用golang去解析php序列化的字串,在github上找了個解析的包,但是發現解析之後的結果是個interface{ }類型。
頓時我就無從下手了,總在想資料其實是一個map,但是解析後得到一個interface{} , 這讓我怎麼用啊
感覺需要用型別斷言,但又不太會用,遂去社區問一下吧,期望大佬們能給個答案。
其實確實很管用。
下面貼一下程式碼:
package main import ( "github.com/yvasiyarov/php_session_decoder/php_serialize" "fmt" "log" ) func main() { // 序列化后的字符串 str := `a:3:{s:4:"name";s:3:"tom";s:3:"age";s:2:"23";s:7:"friends";a:2:{i:0;a:1:{s:4:"name";s:5:"jerry";}i:1;a:1:{s:4:"name";s:4:"jack";}}}` // 反序列化 decoder := php_serialize.NewUnSerializer(str) if result, err := decoder.Decode(); err != nil { panic(err) } else { // 此处进行类型断言 decodeData, ok := result.(php_serialize.PhpArray) if !ok { log.Println(err) } // 断言后,即可获取内容 name := decodeData["name"] age := decodeData["age"] fmt.Println(name, age) // 内层数据仍需再次断言 friends, ok := decodeData["friends"].(php_serialize.PhpArray) if !ok { log.Println(err) } // 断言成功后即可获取内部数据 for _,v := range friends { fmt.Printf("type:%T, value:%+v\n", v,v ) friend, ok := v.(php_serialize.PhpArray) if !ok { log.Println(err) } friendName := friend["name"] fmt.Println(friendName) } } }
可以粗暴的這麼理解:一個變數是什麼類型,就進行什麼類型的斷言,斷言後,即可得到結果
怎麼判斷一個變數的類型?
印出來呀:fmt.Printf("%T", verb)
#%T這個佔位符可以顯示變數的型別
下面還有個範例:
package main import ( "github.com/yvasiyarov/php_session_decoder/php_serialize" "fmt" "log" ) func main() { // 序列化后的字符串 str := `a:3:{s:4:"name";s:3:"tom";s:3:"age";s:2:"23";s:7:"friends";a:2:{i:0;a:1:{s:4:"name";s:5:"jerry";}i:1;a:1:{s:4:"name";s:4:"jack";}}}` // 反序列化 decoder := php_serialize.NewUnSerializer(str) result, err := decoder.Decode() if err != nil { panic(err) } // 类型断言 t := result.(php_serialize.PhpArray) strVal := php_serialize.PhpValueString(t["name"]) fmt.Println(strVal) switch t := result.(type) { default: fmt.Printf("unexpected type %T\n", t) case php_serialize.PhpArray: fmt.Println(t) fmt.Println(t["name"]) fmt.Println(t["age"]) switch f := t["friends"].(type) { default: fmt.Printf("unexpected type %T\n", t) case php_serialize.PhpArray: fmt.Println(f) fmt.Println(f[0]) fmt.Println(f[1]) } } }
上面兩個demo都可以達到效果,只是寫法不同。
後面我又經人介紹,得到了另外一個包,也能達到效果:
package main import ( "fmt" "log" "github.com/wulijun/go-php-serialize/phpserialize" ) func main() { str := `a:3:{s:4:"name";s:3:"tom";s:3:"age";s:2:"23";s:7:"friends";a:2:{i:0;a:1:{s:4:"name";s:5:"jerry";}i:1;a:1:{s:4:"name";s:4:"jack";}}}` decodedRes, err := phpserialize.Decode(str) if err != nil { panic(err) } //fmt.Printf("%T\n", decodedRes) //type is map[interface{}]interface{} //type assert decodedData, ok := decodedRes.(map[interface{}]interface{}) if !ok { fmt.Printf("unexpected type %T\n", decodedRes) } fmt.Println(decodedData["name"]) fmt.Println(decodedData["age"]) //fmt.Printf("%T\n", decodedData["friends"]) // type is map[interface{}]interface{} // type assert friendsRes, ok := decodedData["friends"].(map[interface{}]interface{}) if !ok { fmt.Printf("unexpected type %T\n", decodedData["friends"]) } for _,v := range friendsRes { //fmt.Printf("type: %T, val: %#v\n", v,v) // type is map[interface{}]interface{} friend, ok := v.(map[interface{}]interface{}) if !ok { fmt.Printf("unexpected type %T\n", decodedData["friends"]) } //fmt.Printf("type: %T, val: %#v\n", friend,friend) // type is map[interface{}]interface{} fmt.Println(friend["name"]) } }
這個包解析出來的所有結果的類型都是map[interface{}]interface{ },所以做型別斷言的時候可以簡單粗暴一些。
以上是了解學習golang類型斷言的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

在Go中安全地讀取和寫入檔案至關重要。指南包括:檢查檔案權限使用defer關閉檔案驗證檔案路徑使用上下文逾時遵循這些準則可確保資料的安全性和應用程式的健全性。

如何為Go資料庫連線配置連線池?使用database/sql包中的DB類型建立資料庫連線;設定MaxOpenConns以控制最大並發連線數;設定MaxIdleConns以設定最大空閒連線數;設定ConnMaxLifetime以控制連線的最大生命週期。

可以透過使用gjson函式庫或json.Unmarshal函數將JSON資料儲存到MySQL資料庫中。 gjson函式庫提供了方便的方法來解析JSON字段,而json.Unmarshal函數需要一個目標類型指標來解組JSON資料。這兩種方法都需要準備SQL語句和執行插入操作來將資料持久化到資料庫中。

GoLang框架與Go框架的差異體現在內部架構與外部特性。 GoLang框架基於Go標準函式庫,擴充其功能,而Go框架由獨立函式庫組成,以實現特定目的。 GoLang框架更靈活,Go框架更容易上手。 GoLang框架在效能上稍有優勢,Go框架的可擴充性更高。案例:gin-gonic(Go框架)用於建立RESTAPI,而Echo(GoLang框架)用於建立Web應用程式。

後端學習路徑:從前端轉型到後端的探索之旅作為一名從前端開發轉型的後端初學者,你已經有了nodejs的基礎,...

FindStringSubmatch函數可找出正規表示式匹配的第一個子字串:此函數傳回包含匹配子字串的切片,第一個元素為整個匹配字串,後續元素為各個子字串。程式碼範例:regexp.FindStringSubmatch(text,pattern)傳回符合子字串的切片。實戰案例:可用於匹配電子郵件地址中的域名,例如:email:="user@example.com",pattern:=@([^\s]+)$獲取域名match[1]。

Go框架開發常見問題:框架選擇:取決於應用需求和開發者偏好,如Gin(API)、Echo(可擴展)、Beego(ORM)、Iris(效能)。安裝和使用:使用gomod指令安裝,導入框架並使用。資料庫互動:使用ORM庫,如gorm,建立資料庫連線和操作。身份驗證和授權:使用會話管理和身份驗證中間件,如gin-contrib/sessions。實戰案例:使用Gin框架建立一個簡單的部落格API,提供POST、GET等功能。

Go語言中使用預先定義時區包含下列步驟:匯入"time"套件。透過LoadLocation函數載入特定時區。在建立Time物件、解析時間字串等操作中使用已載入的時區,進行日期和時間轉換。使用不同時區的日期進行比較,以說明預先定義時區功能的應用。
