循环和分支
本章学习目标
学会使用计算机通过if和switch做选择
学会使用for循环重复执行指定的代码
学会基于条件实现循环和分支处理
3.1 真或假
-
Booleas 类型
- 两个预声明长量true和flase用于判断是真是假
- 区别于python和js把空字符和空列表也表示假
-
Strings,Contains
- 来自strings包的Contains函数可以判断某个字符串是否包含另外的字符串
-
例子(3.1)
package main import ( "fmt" "strings" ) func main() { fmt.Println("You fond yourself in a dimly lit cavern.") var command = "walk outside" var exit = strings.Contains(command, "outside") fmt.Println("You leave the cave;", exit) } 执行结果: You fond yourself in a dimly lit cavern. You leave the cave; true
3.2 比较
-
如果我们比较两个值、得到的结果也是true或者false
-
比较运算符:
- ==
- <=
- <
- !=
- 大于等于
- 大于
-
例子(3.2)
package main import ( "fmt" ) func main() { fmt.Println("There is a sign near the entrance that reads 'No Minors'") var age = 41 var minor = age < 18 fmt.Printf("At age %v, am I a minor? %v\n", age, minor) } 执行结果: There is a sign near the entrance that reads 'No Minors' At age 41, am I a minor? false
3.3 用if做分支
-
直接看例子(3.3)
package main import ( "fmt" ) func main() { var command = "go east" if command == "go east" { fmt.Println("You head further up the mountain.") } else if command == "go inside" { fmt.Println("You enter the cave where you live out the rest of your life") } else { fmt.Println("Didn't quite get that.") } } 执行结果: You head further up the mountain.
-
在这里else if 和else都是可选择的
-
else if 可以为多个
3.4 逻辑运算符
-
|| 表示或、&& 表示与,它们用来同时检查多个条件
-
例子(3.4)
package main import ( "fmt" ) func main() { fmt.Println("The year is 2100, should you leap?") var year = 2100 var leap = year%4 == 0 || (year%4 == 0 && year%100 != 0) if leap { fmt.Println("Look before you leap!") } else { fmt.Println("Keep your feet on the ground") } } 执行结果: The year is 2100, should you leap? Look before you leap!
-
逻辑或中会使用一种叫做短路逻辑(当第一个条件为true时就不会走第二个条件)
-
取反逻辑运算符
- !,可以把true变成false,反之亦然
3.5 使用switch做分支
-
例子(3.5)
package main import ( "fmt" ) func main() { var command = "go east" switch command { case "go east": fmt.Println("You head further up the mountain.") case "go inside": fmt.Println("You enter the cave where you live out the rest of your life") case "read sign": fmt.Println("The sign reads 'No Minors'.") default: fmt.Println("Didn't quite get that.") } } 执行结果: You head further up the mountain.
-
Switch 语句也可以对数字进行匹配
-
还有一个fallthrough关键字,它用来执行下一个case
-
例子(3.5.1)
package main import ( "fmt" ) func main() { var room = "lake" switch { case room == "cave": fmt.Println("this cave") case room == "lake": fmt.Println("this lake") fallthrough case room == "underwater": fmt.Println("执行fall") } } 执行结果: this lake 执行fall
-
3.6 使用循环做重复
-
for 关键字可以让你的代码重复执行
-
for 后边不跟条件,那就是无限循环
-
可以用break跳出循环
-
例子
package main import ( "fmt" "time" ) func main() { var count = 10 for { fmt.Println(count) if count <= 0 { break } time.Sleep(time.Second) count-- } fmt.Println("end") } 执行结果: 10 9 8 7 6 5 4 3 2 1 0 end
-