[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