停止处理带有用户输入的for循环。

huangapple go评论86阅读模式
英文:

Stop Processing For loop with User Input

问题

我是你的中文翻译助手,以下是翻译好的内容:

我对Golang还不熟悉。我正在尝试在Golang中提供一种退出长循环的方法。这个循环遍历一个包含700多个项目的数组。我想给最终用户一个点击X的选项来中断循环。我尝试使用reader := bufio.NewReader(os.Stdin),但这样每次进入循环时都会等待输入。如何判断用户是否按下了某个键,并在不每次都等待输入的情况下退出循环呢?

英文:

I'm new to Golang. I am trying to provide an exit from processing of a long for loop in golang. The for loop iterates through an array of over 700 items. I would like to give the end user an option to click on X to break the loop.
I tried reader := bufio.NewReader(os.Stdin), but then it waits for input every time it enters the loop. How do you determine if a user has had a keypress and exit the loop without pausing to wait for input each time?

答案1

得分: 0

你可以像下面这样使用goroutine和channel:

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
	"time"
)

func main() {
	stopCh := make(chan bool)

	go func() {
		reader := bufio.NewReader(os.Stdin)
		fmt.Print("输入文本:")
		text, _ := reader.ReadString('\n')
		if strings.TrimSpace(text) == "stop" {
			stopCh <- true
		}
	}()

loop:
	for {
		select {
		case stop := <-stopCh:
			if stop {
				break loop
			}
		default:
			// 长时间处理

			time.Sleep(10 * time.Second)
		}

	}
}

基本上,你创建一个新的goroutine来接收用户输入并将其发送到channel。在主处理循环中,你使用select语句来轮询stop channel,看是否收到了停止命令。如果没有收到停止命令,它会执行默认操作并完成你要求的正常工作。否则,如果收到停止命令,它将跳出for循环。

英文:

You can do something like below to use goroutine and channel.

package main

import (
	&quot;bufio&quot;
	&quot;fmt&quot;
	&quot;os&quot;
	&quot;strings&quot;
	&quot;time&quot;
)

func main() {
	stopCh := make(chan bool)

	go func() {
		reader := bufio.NewReader(os.Stdin)
		fmt.Print(&quot;Enter text: &quot;)
		text, _ := reader.ReadString(&#39;\n&#39;)
		if strings.TrimSpace(text) == &quot;stop&quot; {
			stopCh &lt;- true
		}
	}()

loop:
	for {
		select {
		case stop := &lt;-stopCh:
			if stop {
				break loop
			}
		default:
			// long processing

			time.Sleep(10 * time.Second)
		}

	}
}

Basically you create a new goroutine to take the input from user and then send it to the channel. In the main processing loop. you do a select which will poll the stop channel and see whether any stop command is given, if no, it goes to default and do the normal job you ask to do. Otherwise, if a stop command is received, it will break the for loop.

huangapple
  • 本文由 发表于 2021年6月19日 08:18:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/68042617.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定