Go 切换语句
示例
一个简单的switch声明:
switch a + b {
case c:
//做点什么
case d:
//做点什么 else
default:
//做点什么 entirely different
}上面的示例等效于:
if a + b == c {
//做点什么
} else if a + b == d {
//做点什么 else
} else {
//做点什么 entirely different
}该default子句是可选的,并且仅当所有情况均不为真时才执行,即使它没有出现在最后(也可以接受)。以下在语义上与第一个示例相同:
switch a + b {
default:
//做点什么 entirely different
case c:
//做点什么
case d:
//做点什么 else
}如果您打算fallthrough在default子句中使用该语句,这可能很有用,该子句必须是case中的最后一条语句,并使程序执行继续进行下一种case:
switch a + b {
default:
//做点什么 entirely different, but then also do something
fallthrough
case c:
//做点什么
case d:
//做点什么 else
}空的switch表达式是隐式的true:
switch {
case a + b == c:
//做点什么
case a + b == d:
//做点什么 else
}switch语句支持类似于以下if语句的简单语句:
switch n := getNumber(); n {
case 1:
//做点什么
case 2:
//做点什么 else
}如果案例具有相同的逻辑,则可以将它们组合在以逗号分隔的列表中:
switch a + b {
case c, d:
//做点什么
default:
//做点什么 entirely different
}
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短