if else控制语句
在go中,ifelse语句与其他语言没有本质区别,只有一些书写形式上的差异。如以下代码
package main
import "fmt"
func givemeanumber() int {
return -1
}
func main() {
if num := givemeanumber(); num < 0 {
fmt.Println(num, "is negative")
} else if num < 10 {
fmt.Println(num, "has only one digit")
} else {
fmt.Println(num, "has multiple digits")
}
}
go语言中,else语句和else if语句要放在if语句的大括号后面,不能另起一行,不然会报错。同时,go中图方便,去除了条件的括号,虽然没有括号,但是他类似于隐形的括号,不需要自己打。
Switch语句
相比if else语句,switch语句在go语言中与其他语言有一些区别。go语言中,swtich的东西可以很多变,甚至不要swtich的东西,如下
package main
import "fmt"
func location(city string) (string, string) {
var region string
var continent string
switch city {
case "Delhi", "Hyderabad", "Mumbai", "Chennai", "Kochi":
region, continent = "India", "Asia"
case "Lafayette", "Louisville", "Boulder":
region, continent = "Colorado", "USA"
case "Irvine", "Los Angeles", "San Diego":
region, continent = "California", "USA"
default:
region, continent = "Unknown", "Unknown"
}
return region, continent
}
func main() {
region, continent := location("Irvine")
fmt.Printf("John works in %s, %s\n", region, continent)
}
package main
import (
"fmt"
"time"
)
func main() {
switch time.Now().Weekday().String() {
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday":
fmt.Println("It's time to learn some Go.")
default:
fmt.Println("It's the weekend, time to rest!")
}
fmt.Println(time.Now().Weekday().String())
}
可以看到,switch能够选择方法的返回值,这点很方便,更多的就不赘述了。
for循环
for循环跟其他语言的循环差不多,也不用打括号,但是他有更加方便的循环方式。同时,因为没有while循环和do while循环,实际上,这两种的循环方式都集成在了for循环里面,如下
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
var num int64
rand.Seed(time.Now().Unix())
for num != 5 {
num = rand.Int63n(15)
fmt.Println(num)
}
}
go中,可以使用range来方便循环,如下
for i, num := range nums { if num == 3 { fmt.Println("index:", i) } }
i是下标,num是数组nums的值,如果下标或者值可以直接用下划线_来代替。
defer函数
在 Go 中,defer 语句会推迟函数(包括任何参数)的运行,直到包含 defer 语句的函数完成。 通常情况下,当你想要避免忘记任务(例如关闭文件或运行清理进程)时,可以推迟某个函数的运行。
可以根据需要推迟任意多个函数。 defer 语句按逆序运行,先运行最后一个,最后运行第一个。
package main
import (
"io"
"os"
"fmt"
)
func main() {
newfile, error := os.Create("learnGo.txt")
if error != nil {
fmt.Println("Error: Could not create file.")
return
}
defer newfile.Close()
if _, error = io.WriteString(newfile, "Learning Go!"); error != nil {
fmt.Println("Error: Could not write to file.")
return
}
newfile.Sync()
}
创建或打开某个文件后,可以推迟 .Close() 函数的执行,以免在你完成后忘记关闭该文件。