Go 斷言


斷言

golang中的所有程序都實現了interface{}的接口,這意味着,所有的類型如string,int,int64甚至是自定義的struct類型都就此擁有了interface{}的接口,這種做法和java中的Object類型比較類似。
那么在一個數據通過func funcName(interface{})的方式傳進來的時候,也就意味着這個參數被自動的轉為interface{}的類型。

如以下的代碼:

func funcName(a interface{}) string {
     return string(a)
}

編譯器將會返回:

cannot convert a (type interface{}) to type string: need type assertion

此時,意味着整個轉化的過程需要類型斷言

直接斷言使用

var a interface{}

fmt.Println("Where are you,Jonny?", a.(string))

但是如果斷言失敗一般會導致panic的發生。所以為了防止panic的發生,我們需要在斷言前進行一定的判斷

value, ok := a.(string)

如果斷言失敗,那么ok的值將會是false,但是如果斷言成功ok的值將會是true,同時value將會得到所期待的正確的值

value, ok := a.(string)
if !ok {
    fmt.Println("It's not ok for type string")
    return
}
fmt.Println("The value is ", value)

switch判斷

var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
    fmt.Printf("unexpected type %T", t)       // %T prints whatever type t has
case bool:
    fmt.Printf("boolean %t\n", t)             // t has type bool
case int:
    fmt.Printf("integer %d\n", t)             // t has type int
case *bool:
    fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
case *int:
    fmt.Printf("pointer to integer %d\n", *t) // t has type *int
}

一般swicth的用處會多點。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM