## 一、簡單斷言
直接定義一個interface類型變量,然后獲取type判斷
```
package main
import "fmt"
type Element interface{}
func main() {
var e Element = 100
switch value := e.(type) {
case int:
fmt.Println("int", value) // 這里的value也可以寫成e.(int),是一樣的
case string:
fmt.Println("string", value)
default:
fmt.Println("unknown", value)
}
}
```
打印結果:
```
int 100
```
## 二、函數方式
以函數形式,傳入interface參數
```
package main
import "fmt"
func add(a, b interface{}) {
switch t := a.(type) {
case int:
fmt.Printf("type [%T] add res[%d]\n", t, a.(int)+b.(int))
case int16:
fmt.Printf("type [%T] add res[%d]\n", t, a.(int16)+b.(int16))
case float32:
fmt.Printf("type [%T] add res[%f]\n", t, a.(float32)+b.(float32))
case float64:
fmt.Printf("type [%T] add res[%f]\n", t, a.(float64)+b.(float64))
default:
fmt.Printf("type [%T] not support!\n", t)
}
}
func main() {
add(1, 2)
add(int16(1), int16(2))
add(float32(1.1), float32(2.2))
add(float64(1.1), float64(2.2))
add(true, false)
}
```
打印結果:
```
type [int] add res[3]
type [int16] add res[3]
type [float32] add res[3.300000]
type [float64] add res[3.300000]
type [bool] not support!
```
## 三、先判斷后使用
以上斷言.(type)只能與switch配合使用,在使用前得用斷言指明變量的類型,如果斷言錯誤就會觸發panic。
如果不想觸發panic,先做判斷再使用,如下:
```
package main
import "fmt"
func main() {
a := int16(2)
b := int32(3)
add(a, b)
}
func add(a, b interface{}) {
_, ok := a.(int32)
if !ok {
fmt.Println("error type assertion!")
} else {
fmt.Println(b)
}
}
```
打印結果:
```
error type assertion!
```