我试图在3秒内以编程方式结束终端输入并输出结果。
我的代码如下:
package main
import (
"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 milliseconds
hello It's time to break input and read what you have already typed
result
我刚刚打印hello
并且过了3秒,程序应该结束输入并读取我的hello
并输出:
result
hello
但我不知道如何提供这个。是否可以在没有用户意图的情况下结束终端输入并读取输入值?
答案 0 :(得分:2)
你不能直接超时读取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")
}
}