接口斷言
因為空接口 interface{}沒有定義任何函數,因此 Go 中所有類型都實現了空接口。當一個函數的形參是interface{},那么在函數中,需要對形參進行斷言,從而得到它的真實類型。
語法格式:
// 安全類型斷言
<目標類型的值>,<布爾參數> := <表達式>.( 目標類型 )
//非安全類型斷言
<目標類型的值> := <表達式>.( 目標類型 )
示例代碼:
package main
import "fmt"
func main() {
var i1 interface{} = new (Student)
s := i1.(Student) //不安全,如果斷言失敗,會直接panic
fmt.Println(s)
var i2 interface{} = new(Student)
s, ok := i2.(Student) //安全,斷言失敗,也不會panic,只是ok的值為false
if ok {
fmt.Println(s)
}
}
type Student struct {
}
斷言其實還有另一種形式,就是用在利用 switch語句判斷接口的類型。每一個case會被順序地考慮。當命中一個case 時,就會執行 case 中的語句,因此 case 語句的順序是很重要的,因為很有可能會有多個 case匹配的情況。
示例代碼:
switch ins:=s.(type) {
case Triangle:
fmt.Println("三角形。。。",ins.a,ins.b,ins.c)
case Circle:
fmt.Println("圓形。。。。",ins.radius)
case int:
fmt.Println("整型數據。。")
}