一个简单的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
}