Golang for loop - tutorial and examples

In this tutorial you will see and learn how to use the golang for loop functionality. A for loop is used to loop a specific block of code for the number of times you wish, or to iterate through your data and use them. In this tutorial you will see how to define the for loop statement in go, and how to iterate a data list in go.

The for loop

The for loop repeats a block of code until a condition is met. The syntax is the following:

for initialization variable i; condition on variable i; update variable i {
  repeat some code
}

You have to initialize the variable that will be used to met the for loop condition, check at every loop the condition, if is met, and increment the variable after every loop succeed.

Example

for i := 0; i < 10; i++ {
 fmt.Println(i)
}

In this example, we initialize the i variable with a value of zero.

After every loop we check if the i variable is less or equal than 10. Till when the i variable is less than 10, the loop is repeated. When i reached 10, the loop is stopped.

And we increment 1 after every loop

With this conditions, the loop is repeated exactly 10 times, from 0 to 9.

Example 2 iterate over your data with for .. range loop

Let's define a prefilled variable. This will be a simple list of strings.

The for range loop is defined as follows:

        list := []string{
		"a",
		"b",
		"c",
	}

	for index, row := range list {
		fmt.Println(index, row)
	}

You can use the index of the item and the data item defined in the row variable. If you don't need to use the index, just replace index with the underscore _ like:

        list := []string{
		"a",
		"b",
		"c",
	}

	for _, row := range list {
		fmt.Println(row)
	}

 

Other articles