package main
 
import "fmt"
 
func main() {
    // 第一种写法
    for i := 1;i < 10; i++ {
        fmt.Println("Hello Golang");
    }
 
    // 第二种写法
    j := 1
    for j < 10 {
        fmt.Println("Hello Go")
        j++
    }
 
    // for 死循环,通常配合break使用
    k := 1
    for {
        if k <= 10 {
            fmt.Println("Hello")
        } else {
            break
        }
        k++
 
    }
}

 

其他语言通常都有 for, while, do while 几种循环。但是 Go 只有一种 for 循环,是因为设计者认为,只需要 for 循环就已经足够完成 while 和 do while 的功能。

3 part loop, 类似于 C 中最常见的 for loop
for i := 0; i <= 10; i++ {
}
1
2
while loop
for x == true {
}
1
2
do while loop
for {
if x {
break;
}
}
1
2
3
4
5
infinite loop
for {
}
1
2

小公鸡卡哇伊呀~
关注

1


0

0

 

 

 

Go语言和其他语言不一样,它只有一种循环方式,就是for语句

可以参考如下公式:

1
2
3
for initialisation; condition; post{
    //Do Something
}

执行顺序

  • a.执行一次initialisation,初始化
  • b.判断condition
  • c.条件为true,执行{}内的语句
  • d.语句执行之后执行post

使用方式举例:

1.基本使用类似其他语言的for

1
2
3
4
5
6
func ForTest1(){
   for i:=1;i<=10;i++{
      fmt.Printf("i=%d\t",i)
   }
   fmt.Println()
}

2.替代while语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func ForTest2(){
   i:=1
   for  ;i<=10; {
      i=i+2
      fmt.Printf("i=%d\t",i)
   }
   fmt.Println()
  
   //等价于
   for i<=10 {
      i=i+2
      fmt.Printf("i=%d\t",i)
      fmt.Println()
   }
}

3.多条件(多重赋值)

1
2
3
4
5
6
7
8
func ForTest3(){
   for x,y:=1,10; x<10 && y>1; x,y = x+1,y-1{
      fmt.Printf("x=%d\t",x)
      fmt.Printf("y=%d\t",y)
      fmt.Println()
   }
   fmt.Println()
}

4.无限循环

1
2
3
4
5
6
7
8
9
10
func ForTest4(){
   count:=1
   for {
      fmt.Printf("Hello\t")
      if(count == 3){
         break
      }
      count++
   }
}
posted on 2022-08-20 11:57  del88  阅读(249)  评论(0编辑  收藏  举报