English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang Basic Tutorial

Golang Control Statement

Golang Function & Method

Golang Struct

Golang Slice & Array

Golang String (String)

Golang Pointer

Golang Interface

Golang Concurrency

Golang Exception (Error)

Golang Miscellaneous

Go language loop statements (for loop)

The for loop in the Go language is a repeating control statement that allows us to write loops that execute a specific number of times. In the Go language, this for loop can be used in different forms, including:

1. Simple for loopWe use similar constructs in other programming languages (such as C, C ++similarly used in other programming languages (such as Java, C#, etc.).

Syntax:

for initialization; condition; post{
       // statements....
}

Here,

  • InInitialization (initialization)The initialization statement is optional and is used to execute before the loop starts. The initialization statement is always placed within simple statements, such as variable declarations, increment or assignment statements, or function calls.

  • The condition (condition) statement contains a boolean expression that is calculated at the beginning of each iteration of the loop. If the value of the condition statement is true, the loop is executed.

  • The post statement is executed after the for loop body. After the post statement, the condition statement is recalculated to check if its value is false, and then the loop ends.

//Using for loop  
package main 
  
import "fmt"
  
//Main function 
func main() { 
      
    // for loop
        //This loop starts executing when i = 0, until i <4The condition is true
        //The post statement is i++
    for i := 0; i < 4; i++{ 
      fmt.Printf("w3codebox\n")   
    } 
    
}

Output:

w3codebox
w3codebox
w3codebox
w3codebox

2. Using for loop as an infinite loop:By removing all three expressions from the for loop, the for loop can also be used as an infinite loop. If the user does not write a condition statement in the for loop, it means that the condition statement is true, and the loop enters an infinite loop.

Syntax:

for{
     // statements...
}
// Using infinite loop  
package main 
  
import "fmt"
   
func main() { 
      
    // Infinite loop 
    for { 
      fmt.Printf("w3codebox\n")   
    } 
    
}

Output:

w3codebox
w3codebox
w3codebox
w3codebox
w3codebox
w3codebox
w3codebox
w3codebox
w3codebox
w3codebox
...........

3. Using for loop as a while loop: The for loop can also be used as a while loop. Execute this loop until the given condition is true. The loop ends when the value of the given condition is false.

Syntax:

for condition {
    //statement..
}
//The for loop is the same as the while loop 
package main 
  
import "fmt"
   
func main() { 
      
      //While loop
      //The for loop executes until
      //i <3The condition is true
    i := 0 
    for i < 3 { 
       i += 2 
    } 
  fmt.Println(i)  
}

Output:

4

4. Simple range in the for loop:You can alsoWithin the for loopUsing range.

Syntax:

for i, j := range rvariable {
   // statement..
}

Here,

  • i and j are variables assigned iteration values. They are also known as iteration variables.

  • The second variable, i.e., j, is optional.

  • The range expression is evaluated once before the loop starts.

package main 
  
import "fmt"
func main() { 
      
    //Here, rvariable is an array 
    rvariable := []string{"GFG", "Geeks", "w"}3codebox"}  
      
        //i and j store the values of rvariable
        //i stores the index number of the single string
        //j stores the single string of the given array
    for i, j := range rvariable { 
       fmt.Println(i, j)  
    } 
    
}

Output:

0 GFG
1 Geeks
2 w3codebox

5. Use for loop for string: The for loop can iterate over the Unicode code points of the string.

Syntax:

for index, chr := range str{
     // statement..
}

here, the index is storing UTF-8the variable for the first byte of the encoding code point, whilechr isis a variable storing the characters of the given string, whilestris a string.

package main
import "fmt"
func main() {
    // String as range in for loop:
    for i, j := range "XabCd" {
        fmt.Printf("%U with the index value %d\n", j, i)
    }
}

Output:

U+0058 with the index value of 0
U+0061 with the index value of 1
U+0062 with the index value of 2
U+0043 with the index value of 3
U+0064 with the index value of 4

6. Use for loop for map: The for loop can iterate overmapkey-value pairs.

Syntax:

for key, value := range map { 
     // statement.. 
}
package main
import "fmt"
func main() {
    
        22
        33: "GFG",
        44: "w3codebox",
    }
    for key, value := range mmap {
        fmt.Println(key, value)
    }
}

Output:

22 Geeks
33 GFG
44 w3codebox

7. For channel: The for loop can iterate over the ordered values sent on the channel until it is closed.

Syntax:

for item := range Chnl { 
   // statement..
}
package main
import "fmt"
func main() {
    // Using channel
    chnl := make(chan int)
    go func() {
        chnl <- 100
        chnl <- 1000
        chnl <- 10000
        chnl <- 100000
        close(chnl)
    }()
    for i := range chnl {
        fmt.Println(i)
    }
}

Output:

100
1000
10000
100000

Important:

  • Brackets are not used in the three statements of the for loop.

  • Curly braces are required in the for loop.

  • The left parenthesis should be on the same line as the post statement.

  • If the array, string, slice, or map collection is empty, the for loop will not throw an error and continue its process. In other words, if the array, string, slice, or map is nil, the iteration count of the for loop is zero.