我试图在 3 秒内以编程方式结束终端输入并输出结果。我的代码如下:package mainimport ( "bufio" "fmt" "os" "time")var ( result string err error)func main() { fmt.Println("Please input something, you have 3000 milliseconds") go func() { time.Sleep(time.Millisecond * 3000) fmt.Println("It's time to break input and read what you have already typed") fmt.Println("result") fmt.Println(result) }() in := bufio.NewReader(os.Stdin) result, err = in.ReadString('\n') if err != nil { fmt.Println(err) }}输出:Please input something, you have 3000 millisecondshello It's time to break input and read what you have already typedresult我刚刚打印了hello3 秒钟,程序应该结束输入并读取我的hello并给出输出:resulthello但我不知道如何提供这个。是否可以在没有用户意图的情况下结束终端输入并读取输入的值?
1 回答
Qyouu
TA贡献1786条经验 获得超11个赞
您不能直接在 stdin 上超时读取,因此您需要在从读取 goroutine 接收结果周围创建超时:
func getInput(input chan string) {
in := bufio.NewReader(os.Stdin)
result, err := in.ReadString('\n')
if err != nil {
log.Fatal(err)
}
input <- result
}
func main() {
input := make(chan string, 1)
go getInput(input)
select {
case i := <-input:
fmt.Println(i)
case <-time.After(3000 * time.Millisecond):
fmt.Println("timed out")
}
}
- 1 回答
- 0 关注
- 294 浏览
添加回答
举报
0/150
提交
取消