GoLang : Loops and conditions

Go uses a single for loop to handle every looping scenario. Learn how to use it as a basic loop, a while loop, an infinite loop, and a for range loop with practical code examples.

Loops and conditions are fundamental structures of any programming language. They are commonly called control structures. if-else and switch control which execution path the program chooses, while loops control how many times a block of code runs. While other programming languages have while, do-while, and for loops, Go has only the for loop.

While there is only one for loop, it is designed in a very flexible way.

for InitStatement;Condition;PostStatement{
//code
}
  1. InitStatement – Executes only once before the loop starts. It is used for initialization.
  2. Condition – Evaluated before each iteration to check if the loop should run again.
  3. PostStatement – Executes after each iteration of the loop body.

However, all three are optional, so you can use them based on the scenario.

Basic For Loop

This is similar to what you may have seen in other languages.

for i := 0; i <= 3; i++ {
  fmt.Println("Hello World")
}

Simulating a While Loop

In Go, there is no separate while keyword. Instead, you can drop the InitStatement and PostStatement and use only the condition. This makes the for loop behave exactly like a while loop in other languages.

i := 0
for i < 5 {
  fmt.Println(i)
  i++
}

Here, the variable i is initialized outside the loop and the increment happens inside the loop body. The loop keeps running as long as i < 5 is true. This is the Go equivalent of while (i < 5) in languages like C or Java.

Infinite Loop

If you omit the condition entirely, you get an infinite loop. This is useful when you want to keep a program running until a specific condition triggers a break from inside the loop body.

count := 0
for {
  fmt.Println("Running...")
  count++
  if count == 3 {
    break
  }
}

This will print “Running…” three times and then exit the loop. Without the break statement, this loop would run forever. Infinite loops are commonly used in server programs that need to continuously listen for incoming requests.

Iterating with Range

The for range loop is used to iterate over data structures like arrays, slices, maps, strings and channels. It provides both the index and the value at each iteration.

Iterating over a slice:

fruits := []string{"apple", "banana", "cherry"}
for index, value := range fruits {
  fmt.Println(index, value)
}

This will output: 0 apple, 1 banana, 2 cherry. If you don’t need the index, you can use the blank identifier _ to ignore it:

for _, value := range fruits {
  fmt.Println(value)
}

Iterating over a map:

colors := map[string]string{"r": "red", "g": "green", "b": "blue"}
for key, value := range colors {
  fmt.Println(key, value)
}

When iterating over a map, for range returns the key and value pairs. Keep in mind that the iteration order over maps in Go is not guaranteed.

Iterating over a string:

for index, char := range "GoLang" {
  fmt.Printf("%d: %c\n", index, char)
}

When ranging over a string, the index is the byte position and the value is the Unicode code point (rune). This makes it safe to iterate over strings that contain multi-byte characters.

For with Continue and Break

Go supports break and continue statements to control the flow inside loops. The break statement exits the loop entirely, while continue skips the current iteration and moves to the next one.

for i := 0; i < 10; i++ {
  if i == 5 {
    break // exits the loop when i is 5
  }
  if i%2 == 0 {
    continue // skips even numbers
  }
  fmt.Println(i)
}

This will only print 1 and 3. The even numbers are skipped by continue, and the loop exits entirely once i reaches 5 because of break.

As you can see, Go’s single for loop keyword can handle every looping scenario you might need. By dropping or adding the init, condition, and post statements you can replicate the behavior of while loops, do-while loops, for-each loops and more all with one clean syntax.

srnyapathi
srnyapathi
Articles: 41