在 golang 终端应用程序中以编程方式结束输入

我试图在 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

我刚刚打印了hello3 秒钟,程序应该结束输入并读取我的hello并给出输出:


result

hello

但我不知道如何提供这个。是否可以在没有用户意图的情况下结束终端输入并读取输入的值?


慕斯王
浏览 295回答 1
1回答

Qyouu

您不能直接在 stdin 上超时读取,因此您需要在从读取 goroutine 接收结果周围创建超时:func getInput(input chan string) {&nbsp; &nbsp; in := bufio.NewReader(os.Stdin)&nbsp; &nbsp; result, err := in.ReadString('\n')&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; }&nbsp; &nbsp; input <- result}func main() {&nbsp; &nbsp; input := make(chan string, 1)&nbsp; &nbsp; go getInput(input)&nbsp; &nbsp; select {&nbsp; &nbsp; case i := <-input:&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(i)&nbsp; &nbsp; case <-time.After(3000 * time.Millisecond):&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("timed out")&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go