SoFunction
Updated on 2025-03-04

Introduction to the usage of looping Loop in Go language

Go language is different from other languages. It only has one loop method, which is for statements.

You can refer to the following formula:

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

Execution order

  • a. Execute initialisation once, initialize
  • b.Judge condition
  • c. The condition is true, execute the statement in {}
  • d. After the statement is executed, the post is executed

Examples of usage:

1. Basically use for similar to other languages

func ForTest1(){
   for i:=1;i<=10;i++{
      ("i=%d\t",i)
   }
   ()
}

2. Alternative while statement

func ForTest2(){
   i:=1
   for  ;i&lt;=10; {
      i=i+2
      ("i=%d\t",i)
   }
   ()
 
   //Equivalent to   for i&lt;=10 {
      i=i+2
      ("i=%d\t",i)
      ()
   }
}

3. Multi-condition (multiple assignment)

func ForTest3(){
   for x,y:=1,10; x<10 && y>1; x,y = x+1,y-1{
      ("x=%d\t",x)
      ("y=%d\t",y)
      ()
   }
   ()
}

4. Infinite loop

func ForTest4(){
   count:=1
   for {
      ("Hello\t")
      if(count == 3){
         break
      }
      count++
   }
}

The operation results are as follows:

-----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

This is all about this article about Go Loop Loop. I hope it will be helpful to everyone's learning and I hope everyone will support me more.