A common application of infinite loops is in goroutines, which run in the background as long as the main program does not exit, such as the following logger goroutine:
main.go
package main
import (
"bufio"
"fmt"
"myapp/mylogger"
"os"
"time"
)
func main() {
reader := bufio.NewReader(os.Stdin)
ch := make(chan string)
go mylogger.ListenForLog(ch)
fmt.Println("Enter something")
for i := 0; i < 5; i++ {
fmt.Print("->")
input, _ := reader.ReadString('\n')
ch <- input
// Sleep a second
time.Sleep(time.Second)
}
}
mylogger.go
package mylogger
import "log"
func ListenForLog(ch chan string) {
// infinite loop that never exits
for {
msg := <-ch
log.Println(msg)
}
}