Go 类型切换语句
示例
一个简单的类型开关:
//假设x是类型interface{}的表达式
switch t := x.(type) {
case nil:
//x为零
//t将为interface{}类型
case int:
//x的基础类型为int
//在这种情况下,t也将是int
case string:
//x的基础类型是字符串
//在这种情况下,t也将是字符串
case float, bool:
//x的基本类型是float或bool
//因为我们不知道哪个,所以在这种情况下,t是interface{}类型的
default:
//x的基础类型不是用于测试的任何类型
//t是这种类型的interface{}
}您可以测试任何类型,包括error,用户定义的类型,接口类型和函数类型:
switch t := x.(type) {
case error:
log.Fatal(t)
case myType:
fmt.Println(myType.message)
case myInterface:
t.MyInterfaceMethod()
case func(string) bool:
if t("Hello world?") {
fmt.Println("你好,世界!")
}
}
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短