SSJX.CO.UK
Content

Go Programming - For Loops

Go simplifies a lot of things, one of them is looping. There is only the for loop but there are many ways to use it!

Basic Loops

Classic For Loop

Just like the 'C' language loop but with no brackets. In general there are usually better ways to do this.

for i := 0; i < 10; i++ {
	// Do something 10 times ('i' will be 0 to 9)
}

Infinite Loop

This sort of loop replaces the do/while type loop. Just remember to break out of it!

for {
	// Remember to call break at some point to escape it!
}

Range Loops

Counting

This one is fairly new but simplifies counting from zero. Less typing means less chance of mistakes.

for i := range 10 {
	// Do something 10 times ('i' will be 0 to 9)
}

For Each (Index / Value)

This reads through a collection (array in this example), the i is the item index, v is the value

myarray := [3]int{10,20,30}

for i, v := range myarray {
	fmt.Println(i,v)
}

The output would be:

0, 10
1, 20
2, 30

For Each (Value)

A lot of the time, we are only interested in the array items value so we use the underscore to ignore the index part.

myarray := [3]int{10,20,30}

for _, v := range myarray {
	fmt.Println(v)
}

The output would be:

10
20
30

Break / Continue

Sometimes we may want to exit a loop early or skip a loop, we can do this using break or continue.

Break exits a loop:

for i := range 5 {
	// This will display 0 to 2 and exit at 3
	if i == 3 {
		break
	}
	fmt.Println(v)	
}

The output would be:

0
1
2

Continue skips the rest of the loop and go back to the start of it:

for i := range 5 {
	// This will display 0 to 4 but skip 3
	if i == 3 {
		continue
	}
	fmt.Println(v)	
}

The output would be:

0
1
2
4

Updated (06/08/2026)