您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Go语言中,switch
语句是一种强大的条件控制结构,它比传统的if-else
链更简洁、更易读。本文将介绍Go中switch
的基本用法和一些高级特性。
Go中的switch
基本语法如下:
switch expression {
case value1:
// 代码块1
case value2:
// 代码块2
default:
// 默认代码块
}
day := 3
switch day {
case 1:
fmt.Println("星期一")
case 2:
fmt.Println("星期二")
case 3:
fmt.Println("星期三")
default:
fmt.Println("其他日子")
}
Go允许省略switch
后的表达式,此时相当于switch true
,每个case
表达式都会被求值为布尔值:
num := 75
switch {
case num < 50:
fmt.Println("小于50")
case num >= 50 && num < 100:
fmt.Println("50到100之间")
default:
fmt.Println("大于等于100")
}
一个case
可以包含多个值,用逗号分隔:
month := 4
switch month {
case 1, 3, 5, 7, 8, 10, 12:
fmt.Println("31天")
case 4, 6, 9, 11:
fmt.Println("30天")
case 2:
fmt.Println("28或29天")
}
Go的switch
还可以用于类型判断:
func checkType(x interface{}) {
switch x.(type) {
case int:
fmt.Println("整型")
case string:
fmt.Println("字符串")
case bool:
fmt.Println("布尔型")
default:
fmt.Println("未知类型")
}
}
默认情况下,Go的switch
执行完匹配的case
后会自动退出,使用fallthrough
可以强制执行下一个case
:
num := 1
switch num {
case 1:
fmt.Println("1")
fallthrough
case 2:
fmt.Println("2")
default:
fmt.Println("默认")
}
// 输出:
// 1
// 2
switch
不需要break
语句,默认不会”贯穿”case
表达式可以是任意类型,不限于常量或整数switch
后的表达式,实现更灵活的布尔逻辑通过合理使用switch
语句,可以使Go代码更加简洁和易读,特别是在处理多个条件分支时。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。