[Go] golang x.(type) 用法


golang x.(type) 用法


類型斷言和類型判斷 if 和 type-switch兩種形式

使用類型斷言斷定某個接口是否是指定的類型

 

if這種簡化形式:

if _,ok:=x.(T);ok{

 

}

 

type-switch 類型判斷形式

類型斷言使得相同接口的變量在不同的時刻表現出不同的行為,這就是多態的本質。

func MyPrintf(args ...interface{}) {  
    for _, arg := range args {  
        switch arg.(type) {  
            case int:  
                fmt.Println(arg, "is an int value.")  
            case string:  
                fmt.Println(arg, "is a string value.")  
            case int64:  
                fmt.Println(arg, "is an int64 value.")  
            default:  
                fmt.Println(arg, "is an unknown type.")  
        }  
    }  
}

 

 

在go-imap中看到使用

        switch h := p.Header.(type) {
        case *mail.InlineHeader:
            // This is the message's text (can be plain-text or HTML)
            b, _ := ioutil.ReadAll(p.Body)
            log.Println("Got text: ", string(b))
        case *mail.AttachmentHeader:
            // This is an attachment
            filename, _ := h.Filename()
            log.Println("Got attachment: ", filename)
        }

 

 


免責聲明!

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



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