create a loop in go

In Go, you can create a loop using the for keyword. Here's the basic syntax of creating a loop in Go:

main.go
for initialisation; condition; post {
    // code to be executed
}
67 chars
4 lines
  • The initialisation statement is executed before the loop starts, and is generally used to initialize variables.
  • The condition is a boolean expression that is evaluated before each iteration. If it evaluates to true, the loop continues. If it evaluates to false, the loop terminates.
  • The post statement is executed at the end of each iteration, and is generally used to update variables.

Here's an example of a loop in Go that prints the numbers from 1 to 10:

main.go
package main

import "fmt"

func main() {
    for i := 1; i <= 10; i++ {
        fmt.Println(i)
    }
}
104 chars
10 lines

In this example, we initialize the variable i to 1 in the initialization statement i := 1, set the condition to i <= 10, and increment i by 1 at the end of each iteration with i++. The loop terminates when i becomes greater than 10.

related categories

gistlibby LogSnag