Java
switch(expression){
case value :
//语句
break; //可选
case value :
//语句
break; //可选
//你可以有任意数量的case语句
default : //可选
//语句
}
Go
switch expression{
case val1:
...
case val2:
...
default:
...
}
Java | Go | |
变量expression | byte、short、int 、 char和String | 任何类型 |
break 语句 | 如果当前匹配成功的 case 语句块没有 break 语句,则从当前 case 开始,后续所有 case 的值都会输出,如果后续的 case 语句块有 break 语句则会跳出判断。default不需要break | switch 默认情况下 case 最后自带 break 语句,匹配成功后就不会执行其他 case,如果我们需要执行后面的 case,可以使用 fallthrough |
Type Switch | 无 | switch 语句还可以被用于 type-switch 来判断某个 interface 变量中实际存储的变量类型 |
switch x.(type){
case type:
statement(s);
case type:
statement(s);
/* 你可以定义任意个数的case */
default: /* 可选 */
statement(s);
}