在if之后,条件语句之前,可以添加变量初始化语句,使用;间隔;
在有返回值的函数中,不允许将“终的”return语句包含在if…else…结构中, 否则会编译失败:
function ends without a return statement。
失败的原因在于,Go编译器无法找到终止该函数的return语句。
编译失败的案例如下:
func example(x int) int {
if x == 0 {
return 5
} else {
return x //无法找到终止该函数的return语句
}
}
选择语句
switch i { //i只能为常量或者整数
case 0:
fmt.Printf(“0”)
case 1:
fmt.Printf(“1”)
case 2:
fallthrough //向下执行
case 3:
fmt.Printf(“3”)
case 4, 5, 6: //i等于4|5|6时执行
fmt.Printf(“4, 5, 6”)
default: //其它
fmt.Printf(“Default”)
}
//switch 后也可以不设置表达式:
swi