golang語言如何將interface轉為int, string,slice,struct等型別
阿新 • • 發佈:2020-12-10
在golang中,interface{}
允許接納任意值,int
,string
,struct
,slice
等,因此我可以很簡單的將值傳遞到interface{}
,例如:
package main import ( "fmt" ) type User struct{ Name string } func main() { any := User{ Name: "fidding",} test(any) any2 := "fidding" test(any2) any3 := int32(123) test(any3) any4 := int64(123) test(any4) any5 := []int{1,2,3,4,5} test(any5) } // value 允許為任意值 func test(value interface{}) { ... }
但是當我們將任意型別傳入到test函式中轉為interface後,經常需要進行一系列操作interface不具備的方法(即傳入的User結構體
,interface本身也沒有所謂的Name
屬性),此時就需要用到interface特性type assertions
和type switches
,來將其轉換為回原本傳入的型別
舉個栗子:
package main import ( "fmt" ) type User struct{ Name string } func main() { any := User{ Name: "fidding",5} test(any5) } func test(value interface{}) { switch value.(type) { case string: // 將interface轉為string字串型別 op,ok := value.(string) fmt.Println(op,ok) case int32: // 將interface轉為int32型別 op,ok := value.(int32) fmt.Println(op,ok) case int64: // 將interface轉為int64型別 op,ok := value.(int64) fmt.Println(op,ok) case User: // 將interface轉為User struct型別,並使用其Name物件 op,ok := value.(User) fmt.Println(op.Name,ok) case []int: // 將interface轉為切片型別 op := make([]int,0) op = value.([]int) fmt.Println(op) default: fmt.Println("unknown") } }
執行輸出結果為
fidding true
fidding true
123 true
123 true
[1 2 3 4 5]
可以看到我們可以對interface使用.()
並在括號中傳入想要解析的任何型別,形如
// 如果轉換失敗ok=false,轉換成功ok=true res,ok := anyInterface.(someType)
並且我們並不確定interface型別時候,使用anyInterface.(type)
結合switch case
來做判斷。
現在再回過頭看上面的栗子,是不是更清楚了呢
到此這篇關於golang語言如何將interface轉為int,string,slice,struct等型別的文章就介紹到這了,更多相關golang interface內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!