# 05 控制语句

if语句条件中定义变量是属于局部变量，只有对应的if中的条件和执行语句中有效。
if x > 10 {
fmt.Println("x is greater than 10")
} else {
fmt.Println("x is less than 10")
}

// 计算获取值x,然后根据x返回的大小，判断是否大于10。
if x := computedValue(); x > 10 {
fmt.Println("x is greater than 10")
} else {
fmt.Println("x is less than 10")
}
//这个地方如果这样调用就编译出错了，因为x是条件里面的变量
fmt.Println(x)

if integer == 3 {
fmt.Println("The integer is equal to 3")
} else if integer < 3 {
fmt.Println("The integer is less than 3")
} else {
fmt.Println("The integer is greater than 3")
}

//无限循环 必须要break跳出
a:=1
for{
a++
if a >= 3 {
break
}
}

sum := 1
for sum < 1000 {
sum += sum
}

sum := 1
for ; sum < 1000; {
sum += sum
}

for index := 10; index>0; index-- {
if index == 5{
break // 或者continue
}
fmt.Println(index)
}
// break打印出来10、9、8、7、6
// continue打印出来10、9、8、7、6、4、3、2、1

for配合range可以用于读取slice和map的数据：
for k,v:=range map {
fmt.Println("map's key:",k)
fmt.Println("map's val:",v)
}

for _, v := range map{
fmt.Println("map's val:", v)
}

switch sExpr {
case expr1:
some instructions
case expr2:
some other instructions
case expr3:
some other instructions
default:
other code
}

i := 10
switch i {
case 1://这里可以带条件 和if的条件一样
fmt.Println("i is equal to 1")
case 2, 3, 4:
fmt.Println("i is equal to 2, 3 or 4")
case 10:
fmt.Println("i is equal to 10")
default:
fmt.Println("All I know is that i is an integer")
}

integer := 6
switch integer {
case 4:
fmt.Println("The integer was <= 4")
fallthrough/这个一加后面的case语句都会继续判断和执行 相当于取消了break/
case 5:
fmt.Println("The integer was <= 5")
fallthrough
case 6:
fmt.Println("The integer was <= 6")
fallthrough
case 7:
fmt.Println("The integer was <= 7")
fallthrough
case 8:
fmt.Println("The integer was <= 8")
fallthrough
default:
fmt.Println("default case")
}

Paste_Image.png