Go语言中Loop的注意点

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

可以参考如下公式:

for initialisation; condition; post{
	//Do Something
}

执行顺序

a.执行一次initialisation,初始化

b.判断condition

c.条件为true,执行{}内的语句

d.语句执行之后执行post

 

使用方式举例:

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

func ForTest1(){
   for i:=1;i<=10;i++{
      fmt.Printf("i=%d	",i)
   }
   fmt.Println()
}   

2.替代while语句

func ForTest2(){
   i:=1
   for  ;i<=10; {
      i=i+2
      fmt.Printf("i=%d	",i)
   }
   fmt.Println()

   //等价于
   for i<=10 {
      i=i+2
      fmt.Printf("i=%d	",i)
      fmt.Println()
   }
}

  

3.多条件(多重赋值)

func ForTest3(){
   for x,y:=1,10; x<10 && y>1; x,y = x+1,y-1{
      fmt.Printf("x=%d	",x)
      fmt.Printf("y=%d	",y)
      fmt.Println()
   }
   fmt.Println()
}

  

4.无限循环

func ForTest4(){
   count:=1
   for {
      fmt.Printf("Hello	")
      if(count == 3){
         break
      }
      count++
   }
}  

运行结果如下:

-----ForTest1-------
i=1	i=2	i=3	i=4	i=5	i=6	i=7	i=8	i=9	i=10	
-----ForTest2-------
i=3	i=5	i=7	i=9	i=11	
-----ForTest3-------
x=1	y=10	
x=2	y=9	
x=3	y=8	
x=4	y=7	
x=5	y=6	
x=6	y=5	
x=7	y=4	
x=8	y=3	
x=9	y=2	
-----ForTest4-------
Hello	Hello	Hello	
原文地址:https://www.cnblogs.com/dcz2015/p/10443055.html