6.条件

循环

1
2
for initialization; condition; post {
}

无限循环

1
for {}   

条件循环

1
for condition {}  

遍历数组 , i 是下标

1
2
for i := range arr{    
}

遍历数组, 下标和值

1
2
for index,value := range arr{  
}

range的语法要求,要处理元素,必须处理索引。会拷贝一个新的变量 value , 对 value 做修改不会影响 arr

在 for 多重循环中可以使用 break end 跳出最外层循环, 这里的 eng 是关键字, 有点像是 goto 语句一样

跳出并结束嵌套循环

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
end:
for i := 0; i < 5; i++ {
		for i := 0; i < 10; i++ {
			if i == 2 {
				break end
			}
			fmt.Printf("%d\n", i)
		}
	}
	fmt.Println("end")
}

结果

1
2
3
0
1
end

if 语句

与其他语言的使用区别, 不加括号

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// 如果当前文件夹下有 abcd.txt 文件, 就文件输出内容
// 否则输入错误信息
func main(){
  const filename = "abcd.txt"
  // 返回 []byte 和 错误信息, 变量作用域在 if 语句内
 	if contents ,err := ioutil.ReadFile(filename);err != nil {
    fmt.Println(err)
  }else{
    fmt.Printf("%s\n", contents)
  }
}

switch

  1. switch 会自动 break, 除非使用关键字 fallthrough
  2. switch 后面可以不加表达式, 将表达式放在 case 后面, 逻辑等同 if else
  3. 单个 case 中, 可以出现多个结果, 使用 逗号分隔

image-20210121172133840

Licensed under CC BY-NC-SA 4.0
本文阅读量 次, 总访问量 ,总访客数
Built with Hugo .   Theme Stack designed by Jimmy