文章目录
for 循环
for 是 Go 中唯一的循环结构。这里有 for 循环的三个基本使用方式。
// `for` 是 Go 中唯一的循环结构。这里有 `for` 循环
// 的三个基本使用方式。
package main
import "fmt"
func main() {
// 最常用的方式,带单个循环条件。
i := 1
for i <= 3 {
fmt.Println(i)
i = i + 1
}
// 经典的初始化/条件/后续形式 `for` 循环。
for j := 7; j <= 9; j++ {
fmt.Println(j)
}
// 不带条件的 `for` 循环将一直执行,直到在循环体内使用
// 了 `break` 或者 `return` 来跳出循环。
for {
fmt.Println("loop")
break
}
}
if/else 分支
// `if` 和 `else` 分支结构在 Go 中当然是直接了当的了。
package main
import "fmt"
func main() {
// 这里是一个基本的例子。
if 7%2 == 0 {
fmt.Println("7 is even")
} else {
fmt.Println("7 is odd")
}
// 你可以不要 `else` 只用 `if` 语句。
if 8%4 == 0 {
fmt.Println("8 is divisible by 4")
}
// 在条件语句之前可以有一个语句;任何在这里声明的变量
// 都可以在所有的条件分支中使用。
if num := 9; num < 0 {
fmt.Println(num, "is negative")
} else if num < 10 {
fmt.Println(num, "has 1 digit")
} else {
fmt.Println(num, "has multiple digits")
}
}
// 注意,在 Go 中,你可以不使用圆括号,但是花括号是需要的。
分支结构
// _switch_ ,方便的条件分支语句。
package main
import "fmt"
import "time"
func main() {
// 一个基本的 `switch`。
i := 2
fmt.Print("write ", i, " as ")
switch i {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
}
// 在一个 `case` 语句中,你可以使用逗号来分隔多个表达式。
// 在这个例子中,我们很好的使用了可选的
// `default` 分支。
switch time.Now().Weekday() {
case time.Saturday, time.Sunday:
fmt.Println("it's the weekend")
default:
fmt.Println("it's a weekday")
}
// 不带表达式的 `switch` 是实现 if/else 逻辑的另一种
// 方式。这里展示了 `case` 表达式是如何使用非常量的。
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("it's before noon")
default:
fmt.Println("it's after noon")
}
}
// todo: type switches
更多内容尽在微信公众号 ⌈卡卡成长汇聚⌋