1.分支结构

  1. //if条件判断
  2. score := 65
  3. if score >= 90{
  4. fmt.Println("A")
  5. }else if score > 75 {
  6. fmt.Println("B")
  7. }else {
  8. fmt.Println("C")
  9. }
  1. //特殊写法
  2. if score := 80;score >= 90{
  3. fmt.Println("A")
  4. }else if score > 75 {
  5. fmt.Println("B")
  6. }else {
  7. fmt.Println("C")
  8. }
  1. score :=55
  2. switch {
  3. case score>=90:
  4. fmt.Println("优秀")
  5. case score>=75:
  6. fmt.Println("良好")
  7. case score>=60:
  8. fmt.Println("合格")
  9. case score<60&&score>=0:
  10. fmt.Println("不合格")
  11. default:
  12. fmt.Println("无效的输入")
  13. }
  1. switch n:=7;n{
  2. case 1,3,5,7,9:
  3. fmt.Println("奇数")
  4. case 2,4,6,8:
  5. fmt.Println("偶数")
  6. default:
  7. fmt.Println(n)
  8. }

fallthrough语法可以执行满足条件的case的下一个case,是为了兼容C语言中的case设计的。

  1. switch n:=7;n{
  2. case 1,3,5,7,9:
  3. fmt.Println("奇数")
  4. fallthrough
  5. case 2,4,6,8:
  6. fmt.Println("偶数")
  7. default:
  8. fmt.Println(n)
  9. }

select 语句类似于 switch 语句,但是select会随机执行一个可运行的case。
如果没有case可运行,它将阻塞,直到有case可运行。

  1. var c1,c2,c3 chan int
  2. var i1,i2 int
  3. select {
  4. case i1 = <- c1:
  5. fmt.Println(i1)
  6. case c2 <- i2:
  7. fmt.Println(i2)
  8. case i3,ok := <-c3:
  9. if ok{
  10. fmt.Println(i3)
  11. }else {
  12. fmt.Println("c3 is close")
  13. }
  14. default:
  15. fmt.Println("no communitcation")
  16. }
  17. //no communitcation
  1. func test(ch chan <- int) {
  2. for i := 0; i < 10; i++ {
  3. ch <- i
  4. }
  5. }
  6. var ch = make(chan int)
  7. //超时处理
  8. func main() {
  9. go test(ch)
  10. for {
  11. select {
  12. case data := <-ch:
  13. fmt.Println(data)
  14. case <-time.After(time.Second):
  15. fmt.Println("request time out")
  16. }
  17. }
  18. }
  1. ch := make(chan int,5)
  2. fmt.Println(len(ch)) //0
  3. fmt.Println(cap(ch)) //5
  4. data := 0
  5. select {
  6. case ch <- data:
  7. fmt.Println(len(ch)) //1
  8. fmt.Println(cap(ch)) //5
  9. default:
  10. fmt.Println("default")
  11. }

2.循环结构

所有循环类型均可以使用for关键字来完成

  1. for i := 0;i < 10;i++{
  2. fmt.Println(i)
  3. }

这种写法类似于其他编程语言中的while

  1. i := 0
  2. for i < 10{
  3. fmt.Println(i)
  4. i++
  5. }

2.1无限循环

  1. for {
  2. fmt.Println("循环")
  3. }

2.2键值循环

Go语言中可以使用for range遍历数组、切片、字符串、map 及通道(channel)。 通过for range遍历的返回值有以下规律:

  1. 数组、切片、字符串返回索引和值。
  2. map返回键和值。
  3. 通道(channel)只返回通道内的值。

2.3跳出循环

  1. for i := 0; i < 10; i++ {
  2. if i==5 {
  3. break
  4. }
  5. fmt.Println(i) // 0 1 2 3 4
  6. }

2.4继续下次循环

  1. for i := 0; i < 10; i++ {
  2. if i==5 {
  3. continue
  4. }
  5. fmt.Println(i) //0 1 2 3 4 6 7 8 9
  6. }