在golang中,interface{}
允許接納任意值,int
, string
, struct
,slice
等,因此我可以很簡單的將值傳遞到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", } 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) } 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") } }
輸出結果:
可以看到我們可以對interface使用.()
並在括號中傳入想要解析的任何類型,例如
// 如果轉換失敗ok=false,轉換成功ok=true
res, ok := anyInterface.(someType)
不確定interface類型時候,使用anyInterface.(type)
結合switch case
來做判斷。
現在再回過頭看上面的例子,是不是更清楚了呢