Looping in Go

James Perkins

Posted on January 31, 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) fmt.Println(sumOf)

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

The init statement, i := 0, runs.The condition, i < 5, is evaluated.If it’s true, the loop body executes,otherwise the loop terminates.The post statement, i++, executes.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) fmt.Println(powerOf)

Breaking it down step by step:

The condition, powerOf < 5, is evaluated.If it’s true, the loop body executes,Otherwise the loop terminates.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", "Each","Loops","Are","Done", "With", "Range"} for i, s := range strings { fmt.Println(i, s) }

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

The range expression, strings, is evaluated once before beginning the loop. The iteration values are assigned to the respective iteration variables, i and s, as in an assignment statement. The second iteration variable is optional. 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.


More Posts

Cover Image for Udacity React Nanodegree review - Part 1

Udacity React Nanodegree review - Part 1

I finished the first part of the nanodegree a few days ago and decided to give an indepth review of what is covered, what you learn and what is completed by the end of it.

Cover Image for Why you don't need to be a mathematics genius to be a developer.

Why you don't need to be a mathematics genius to be a developer.

When you first start thinking about becoming a developer, one of the things you might hear is you need to be a math(s) wizz. I am here to tell you that a small number of developers need the mathematics outside of algebra.