Working with For Loop in Go

Unlike other languages, Go has one looping construct — the for loop. However, the for loop can handle all of your looping needs. I will show you examples of how to use the for loop to count from 1 to 10 and how to loop over an array/slice in different ways.

Count From 1 to 10 Using The Standard For Loop

In this example, we use the standard for loop that is available in most programming languages. This code loops from 1 to 10 and prints out the values from 1 to 10.

You can run this in the Go Playground.

This will print the following:

Count From 1 to 10 Using For Loop Like A While Loop

In this example, we use the for loop like a while.

You can run this example in the Go Playground.

This will print the following:

Looping Over An Slice Or an Array

In this example, we create a slice with 10 items. This code loops over the slice and prints the value at the index or the slice/array.

You can run this example in the Go Playground.

This will print the following:

Looping Over a Slice or an Array Using Range

In this example, the code loops through all the elements in an array or slice and prints out their value.

You can run this example in the Go Playground.

This will print the following:

Looping Over a Slice or Array Using Range With Index

In this example, the code loops through all the elements in the array or slice like in the example above. However, the code prints both the index of the element and the element value.

You can run this example in the Go Playground.

This will print the following:

Conclusion

In this blog post, you learn the different ways to use a for a loop.

Harrison Brock