[Go] golang x.(type) 用法
2023-02-18 15:41:52 时间
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) }
相关文章
- Linux系列之链接
- Linux系列之压缩命令
- Linux系列之重定向操作
- Linux系列之比较命令
- Linux系列之管理用户环境变量
- Linux系列之进程管理
- Linux系列之文件和目录权限
- Linux系列之添加和删除软件命令
- Linux系列之文本操作命令
- Linux系列之查找命令
- 基础架构之Gitlab Runner
- 基础架构之GitLab
- 基础架构之Mongo
- 为mongodb添加账号
- MongoDB(online) 优化
- Git使用详细教程(二)
- Git使用详细教程(一)
- 带你上手GitHub的Actions功能
- 【玩转云函数】打通Github到企微的消息通知
- 孙荣辛 | 大数据穿针引线进阶必看——带你盘点那些必知必会的Google经典大数据论文