Golang - 流程控制
Golang - 流程控制
1. 选择结构
if else语句:
//package 声明开头表示代码所属包
package main
import (
"io/ioutil"
"fmt"
)
func main() {
//常量
const filename = "abc.txt"
//读取文件
contens, err := ioutil.ReadFile(filename)
// nil空
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%s
", contens)
}
// ;后边直接去判断和处理了
if contens, err := ioutil.ReadFile(filename); err != nil {
fmt.Println(err)
} else {
fmt.Printf("%s
", contens)
}
}
switch语句:
//package 声明开头表示代码所属包
package main
import "fmt"
//函数传入成绩,得到级别 ABC
func grade(score int) string {
//定义个空串
g := ""
//switch语句
switch {
case score < 0 || score > 100:
g = "输入错误"
//隐式加了一个break,匹配到了就结束
//关键字fallthrough是继续往下跑
fallthrough
case score < 60:
g = "F"
case score < 80:
g = "C"
case score < 90:
g = "B"
case score <= 100:
g = "A"
}
return g
}
func main() {
fmt.Println(
grade(0),
grade(59),
grade(60),
grade(82),
grade(99),
grade(100),
grade(-3),
)
}
//F F C B A A F
2. 循环结构
for 语句:
//package 声明开头表示代码所属包
package main
import (
"fmt"
"time"
)
//1.无限死循环
func for1() {
for {
fmt.Println("爱天台,爱日耳曼战车")
//睡1秒
time.Sleep(1 * time.Second)
}
}
//2.有限次循环
func for2() {
for i := 1; i < 11; i++ {
fmt.Println("爱天台,爱战车", i)
//睡眠
time.Sleep(500 * time.Millisecond)
}
}
//3.if else
func for3() {
for i := 1; i < 11; i++ {
if i%5 == 0 {
fmt.Println("爱阿根廷")
} else if i%2 == 1 {
fmt.Println("更爱战车")
} else {
fmt.Println("最爱是天台")
}
time.Sleep(500 * time.Millisecond)
}
}
func main() {
//for2()
for3()
}
range 语句:
//package 声明开头表示代码所属包
package main
import "fmt"
func main() {
s := "abc"
//1.接收了下标,通过下标取值
for i := range s {
fmt.Printf("下标=%d,值=%c
", i, s[i])
}
//2.直接接收下标和元素值
for i, c := range s {
fmt.Printf("下标2=%d,值2=%c
", i, c)
}
//3.忽略下标
for _, c := range s {
fmt.Printf("值=%c
", c)
}
}
//下标=0,值=a
//下标=1,值=b
//下标=2,值=c
//下标2=0,值2=a
//下标2=1,值2=b
//下标2=2,值2=c
//值=a
//值=b
//值=c
3. 跳转语句
break和continue
//package 声明开头表示代码所属包
package main
import "fmt"
func main() {
for i :=0; i<5; i++{
if 2==i{
//break
continue
}
fmt.Println(i)
}
}
//0
//1
//3
//4
goto:可以跳转到指定的位置运行,注意是跳转到当前函数内
//package 声明开头表示代码所属包
package main
import "fmt"
func main() {
for i :=0; i<5; i++{
fmt.Println(i)
//关键字goto
goto LABEL
}
fmt.Println("程序结束")
LABEL:
fmt.Println("程序over")
}
//0
//程序over