if
if 条件 {
} else if 条件 {
} else {
}
var num = 10
if num > 100 {
println("num > 100")
} else if num >10 {
println("100 >= num > 10")
} else {
println("num <= 10")
}
switch
switch 参数 {
case 值1:
case 值2:
default:
}
var num = 10
switch num {
case 100:
println("num = 100")
case 10:
println("num = 10")
default:
println("默认值")
}
for
for 初始化参数; 条件;每次运行结束需要执行的代码 {
}
var num = 0
for i := 1; i <= 100; i++ {
num += i
}
println(num)
for 条件 {
}
num, i := 0, 1
for i <= 100 {
num += i
i++
}
println(num)
for {}
无限循环, 若想退出,需要break
package main
import (
"fmt"
"time"
)
func main() {
var num int = 1
for {
fmt.Println(num)
time.Sleep(time.Second * 1)
num++
if num >= 5 {
break
}
}
}
for-each
用于遍历容器类型
package main
import (
"fmt"
)
func main() {
var a [3]string
for index := range a {
fmt.Println(index)
a[index] = "asc"
}
for index, value := range a {
fmt.Println(index, value)
}
}
// 0
// 1
// 2
// 0 asc
// 1 asc
// 2 asc