Go语言入门教程:循环与分支结构详解
Go语言作为一种简洁、高效的编程语言,因其优异的并发处理能力和简洁的语法结构而被广泛应用。对于每一位Go语言学习者而言,掌握控制流语句(如循环和分支)是编程的基础。本文将通过详细讲解Go语言中的循环与分支结构,帮助读者理解如何在实际开发中灵活使用这些语法。我们将深入探讨布尔类型、字符串比较、条件判断、逻辑运算符等基础内容,并通过示例代码演示如何在Go语言中实现各种控制流。
本文针对Go语言中的循环与分支结构进行了系统性讲解,适合Go语言的初学者。文章首先介绍了布尔类型的基本概念,以及Go语言中如何使用if、else if和else进行条件判断。接着,通过strings.Contains函数讲解了字符串比较与匹配。本文还详细展示了如何使用逻辑运算符(如&&、||和!)来组合多个条件,进一步提高程序的灵活性。随后,文章介绍了switch语句的多种应用,包括如何用它处理不同的条件匹配,及其与传统语言(如C、Java)的不同之处。最后,文章通过for循环和无限循环的示例,展示了Go语言中循环的多样性以及如何控制循环的退出。
循环和分支
Boolean类型
-
你可能经常会遇到这样的问题:
- 如果你走出了洞穴,那么请翻到21页
-
那么你是否走出了洞穴?
- 这个问题的答案只有true和false两种情况。
- true和false就是两个已声明好的常量。
-
某些语言(例如js)会把“”这种字符串当作false,其他的字符串当作true。
-
而Go语言则不行,只有true是真的,只有false是假的。
strings.Contains
- 来自strings包的Contains函数可以判断某个字符串是否包含另外一个字符串
package main
import (
"fmt"
"strings"
)
// main is the function where it all begins.
func main() {
fmt.Println("You find yourself in a dimly lit cavern.")
var command = "walk outside"
var exit = strings.Contains(command, "outside")
fmt.Println("You leave the cave:", exit)
}
比较
-
如果我们比较两个值,得到的结果也是true或false
-
比较运算符:
- ==
- <=
- <
- !=
- =>
>
package main
import (
"fmt"
)
// main is the function where it all begins.
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)
}
使用if来做分支
package main
import (
"fmt"
)
// main is the function where it all begins.
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.")
}
}
- 在这里else和else if都是可选的
- 而且else if可以重复多个
逻辑运算符
- ||表示或,&&表示与。它们通常用来同时检查多个条件
package main
import (
"fmt"
)
// main is the function where it all begins.
func main() {
fmt.Println("The year is 2100, should you leap?")
var year = 2100
var leap = year%400 == 0 || (year%4 == 0 && year%100 != 0)
if leap {
fmt.Println("Look before you leap!")
} else {
fmt.Println("Keep your feet on the ground.")
}
}
- 这里使用了短路逻辑
取反逻辑运算符
- !,可以把true变为false,反之亦然
package main
import (
"fmt"
)
// main is the function where it all begins.
func main() {
var haveTorch = true
var litTorch = false
if !haveTorch || !litTorch {
fmt.Println("Nothing to see here.")
}
}
使用switch做分支
package main
import (
"fmt"
)
// main is the function where it all begins.
func main() {
fmt.Println("There is cavern entrance here and a path to the east.")
var command = "go inside"
switch command {
case "go east":
fmt.Println("You head further up the mountain.")
case "enter cave", "go inside":
fmt.Println("You find yourself in a dimly lit cavern.")
case "read sign":
fmt.Println("The sign reads 'No Minors'.")
default:
fmt.Println("Didn't quite get that.")
}
}
- switch语句也可以对数字进行匹配
- 还有一个fallthrough关键字,它用来执行下一个case的body部分。这一点与C#、Java等语言不一样。
package main
import (
"fmt"
)
// main is the function where it all begins.
func main() {
var room = "lake"
switch {
case room == "cave":
fmt.Println("You find yourself in a dimly lit cavern.")
case room == "lake":
fmt.Println("The ice seems solid enough.")
fallthrough
case room == "underwater":
fmt.Println("The water is freezing cold.")
}
}
使用循环做重复
-
for关键字可以让你的代码重复执行
-
for后边没有跟条件,那就是无限循环。
- 可以使用break跳出循环
package main
import (
"fmt"
"time"
)
// main is the function where it all begins.
func main() {
var count = 10
for count > 0 {
fmt.Println(count)
time.Sleep(time.Second)
count--
}
// var count = 5
// for {
// if count < 0 {
// break
// }
// fmt.Println(count)
// time.Sleep(time.Second)
// count--
// }
fmt.Println("Liftoff!")
}
作业题
- 实现一个猜数游戏,首先定义一个1-100的整数。然后让计算机生成一个1-100随机数,并显示计算机猜测的结果是太大了还是太小了,没猜对的话就继续猜,直至猜对。
package main
import (
"fmt"
"math/rand"
)
// main is the function where it all begins.
func main() {
var num int
rand_num := random(1, 100)
for {
fmt.Print("请输入一个1-100的整数:")
fmt.Scanln(&num)
// fmt.Printf("扫描结果 num:%d \n", num)
if num > rand_num {
fmt.Println("您猜大了!")
continue
} else if num < rand_num {
fmt.Println("您猜小了!")
continue
} else {
fmt.Println("您猜对了!")
break
}
}
}
func random(min, max int) int {
return rand.Intn(max-min) + min
}
Vscode font:Fira code
总结
通过本文的学习,读者不仅能够掌握Go语言中常见的控制流语句(如if、switch和for),还能够灵活运用布尔类型、逻辑运算符和字符串匹配来实现复杂的条件判断。Go语言的简洁语法使得这些控制结构易于理解与使用,在实际开发中极大提高了代码的可读性与效率。掌握了这些基本知识后,读者能够在编写Go程序时更加得心应手,为后续的更复杂编程任务打下坚实的基础。