原文鏈接:https://www.2cto.com/kf/201712/703563.html
1. 用於判斷變量類型
demo如下:
switch t := var.(type){ case string: //add your operations case int8: //add your operations case int16: //add your operations default: return errors.New("no this type") } } //空接口包含所有的類型,輸入的參數均會被轉換為空接口 //變量類型會被保存在t中
2. 判斷某個接口類型是否實現了特定接口
為實現這一目標,代碼如下:
if t, ok := something.(I) ; ok { // 對於某些實現了接口I的 // t是其所擁有的類型 }
如果已經確定了something實現了接口I,可以直接寫出下面的代碼:
//在確定了something實現了接口I的情況下 //t時something所擁有的類型 //這說明ok t := something.(I)
當然,也可以封裝在一個函數中:
func IsImplement(interface {}) bool{ _, ok := something.(I); return ok }
注意
something必須為接口(Interface)類型,才可以使用類型斷言。假如是其他類型,使用類型斷言時,需要轉換,最好的方法是定義函數,封裝類型斷言方法。
分別運行以下代碼,看看未實現特定接口的類型使用斷言會發生什么:
demo1.go
type I interface{ Get() int Put(int) } //定義結構體,實現接口I type S struct { i int } func (p *S) Get() int { return p.i } func (p *S) Put(v int ) { p.i = v } //使用類型斷言 func GetInt( some interface {}) int { return some.(I).Get() } func main(){ var some = &S{i:5} fmt.Println(GetInt(some)) }
demo2.go
type I interface{ Get() int Put(int) } //定義結構體,實現接口I type S struct { i int } func (p *S) Get() int { return p.i } func (p *S) Put(v int ) { p.i = v } //使用類型斷言 func GetInt( some interface {}) int { return some.(I).Get() } func main(){ var i int = 5 fmt.Println(GetInt(i)) }
