Go 无限循环

  • Post author:
  • Post category:其他


无限循环的一个常见的应用场合是用在 goroutine 中,只要主程序不退出,此goroutine 就一直在在后台执行(running in the background),例如下面的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)
	}
}



版权声明:本文为ftell原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。