In Go, you can create a loop using the for
keyword. Here's the basic syntax of creating a loop in Go:
main.go67 chars4 lines
initialisation
statement is executed before the loop starts, and is generally used to initialize variables.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.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.go104 chars10 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.
gistlibby LogSnag