Select Page

Looping in Go

Written By James Perkins

January 8, 2020

Looping in Go is fairly similar to any other language that you may of seen in the past, with some slight variations that are particular to Go.

Three component Loop

In Go similar to Java, javascript or C# you have the 3 component loop.

sumOf:= 0
for i := 1; i < 5; i++ {
        sumOf += i
// 10 (1+2+3+4)

Breaking this down in to steps of the loop, it works exactly the same manner as JavaScript / Java or C#:

  1. The init statement, i := 0, runs.
  2. The condition, i < 5, is evaluated.
  3. If it’s true, the loop body executes,
  4. otherwise the loop terminates.
  5. The post statement, i++, executes.
  6. Back to step 2.

While loop

The while loop in Go does exist like it does in javascript or Java but you can use the for loop without init and post statement and it will be exactly like a while loop.

powerOf := 1
for powerOf < 5 {
        powerOf *= 2
// 8 (1*2*2*2)

Breaking it down step by step:

  1. The condition, powerOf < 5, is evaluated.
  2. If it’s true, the loop body executes,
  3. Otherwise the loop terminates.
  4. Back to step 1.

For Each Loop

Looping over elements in slices, arrays, maps, channels and strings is done using the range key word, which is far more efficient then writing a for loop.

strings := []string{"For",
"With", "Range"}
for i, s := range strings {
        fmt.Println(i, s)

The step by step process of a for loop with range is:

  1. The range expression, strings, is evaluated once before beginning the loop.
  2. The iteration values are assigned to the respective iteration variables, i and sas in an assignment statement.
  3. The second iteration variable is optional.
  4. If a slice or map is nil, the number of iterations is 0.

That’s the basics of looping in Go, hopefully this will be helpful as you enter into the world of Go.

You May Also Like…

Are you sorted?

Are you sorted?

Go sort package implements sorting for builtins and user-defined types. It's flexibility makes sorting a breeze!...

Git Command Line Basics

Git Command Line Basics

It's 2020, you have started to lean coding it's great to use an GUI like gitKraken however in some roles you might not...


Submit a Comment

Your email address will not be published. Required fields are marked *