Getting started with Go — Loops

Matthew Boyd
1 min readDec 23, 2021

Loops are interesting in Go. From other languages, such as java, we have the following loops:

  • For loops
  • While loops
  • Do while loops

In Go, we only have one loop, the for loop, however, with the for loop, we have the ability to do almost all the functionality of the rest of the loops, we just have to tweak the syntax each time.

For a generic for loop, we have the following syntax:

for var := 1; var < 10; var ++{   fmt.Println(var)
}

For a while loop, we can do the following:

var isMarried bool
counter := 0
for isMarried != true{ if counter == 10{
isMarried = true
}fmt.Println(counter)counter += 1}

A boolean variable will by default be assigned the value of false. Therefore, when we run the while loop until isMarried is turned to true.

We can also have a while loop like so:

counter := 0for{if counter == 10{   break
}
fmt.Println(counter)
counter += 1
}

This will assign a counter variable an enter an infinite loop, we will increment the counter each time, and once the counter has hit 10, it will break the infinite loop.

--

--