开发者社区> 问答> 正文

go程序中switch未匹配的时候如何处理

package main

import "fmt"

func do(i interface{}) {
	switch v := i.(type) {
	case int:
		fmt.Printf("Twice %v is %v\n", v, v*2)
	case string:
		fmt.Printf("%q is %v bytes long\n", v, len(v))
	}
}

func main() {
	do(21)
	do("hello")
	do(true)
}

运行结果

Twice 21 is 42
"hello" is 5 bytes long

还有未匹配的,如何默认处理

展开
收起
水果黄瓜 2021-10-24 09:42:14 820 0
1 条回答
写回答
取消 提交回答
  • 可以通过在switch中,添加default匹配模式

    package main
    
    import "fmt"
    
    func do(i interface{}) {
    	switch v := i.(type) {
    	case int:
    		fmt.Printf("Twice %v is %v\n", v, v*2)
    	case string:
    		fmt.Printf("%q is %v bytes long\n", v, len(v))
            default:
                   fmt.Println("no match")
    	}
    }
    
    func main() {
    	do(21)
    	do("hello")
    	do(true)
    }
    
    2021-10-25 21:43:43
    赞同 展开评论 打赏
问答分类:
Go
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Go语言路上踩过的坑 立即下载
gohbase :HBase go客户端 立即下载
Go构建日请求千亿级微服务实践 立即下载