While True Loop in Go

While loops do not actually exist within Go (golang), by name, but the same functionality is achievable with a for loop. Which is great, why have a ‘while’ when the same can be done with ‘for’.

Our example below shows how you get a Go program to print out a message every second to the screen. (You’ll have to exit to application to stop it, e.g. Ctrl+C)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package main

import (
	"fmt"
	"time"
)

func main() {
	// Example of while true
	for true {
		fmt.Println("Run my code from gophercoding.com")
		time.Sleep(time.Second)
	}
}

If you need to exit this loop, if something went wrong, or a condition was meet then use the break clause.

1
2
3
for true {
	break
}

Equally, if we need to check on a condition, we can replace the true with a variable.

1
2
3
4
5
6
7
8
keepRunning := true
counter := 0
for keepRunning {
	if counter > 50 {
		break
	}
	counter += 1
}

Example In Action

min max in golang