猿问

终端 go 应用程序中的输入超时

我正在尝试制作一个终端golang应用程序,用户有 4 秒的时间输入内容。如果他输入的更快,打印结果并让他再次输入 4 秒。


如果用户不会在 4 秒内返回输入,程序必须编写time out并再次要求他输入。


我的代码做到了这一点,但只有一次。在第一个之后,timeout即使用户在 4 秒内更快,它也不会返回任何结果。我不明白为什么会这样。


编码


package main


import (

    "bufio"

    "fmt"

    "log"

    "os"

    "time"

)


var (

    result string

    err    error

)


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() {

    for {

        fmt.Println("input something")

        input := make(chan string, 1)

        go getInput(input)


        select {

        case i := <-input:

            fmt.Println("result")

            fmt.Println(i)

        case <-time.After(4000 * time.Millisecond):

            fmt.Println("timed out")

        }

    }

}

输出:


input something

123

result

123


input something

2

result

2


input something

timed out

input something

2

timed out

input something

timed out

input something


慕雪6442864
浏览 257回答 1
1回答

哔哔one

问题与您获取用户输入的方式有关。在超时时,您会生成一个新的 go 例程来请求输入,但是您之前生成的旧例程仍在那里获取输入并将其发送到一个没人再收听的频道。将其更改为这样的内容可以解决问题:func getInput(input chan string) {&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; in := bufio.NewReader(os.Stdin)&nbsp; &nbsp; &nbsp; &nbsp; result, err := in.ReadString('\n')&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; input <- result&nbsp; &nbsp; }}func main() {&nbsp; &nbsp; input := make(chan string, 1)&nbsp; &nbsp; go getInput(input)&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("input something")&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case i := <-input:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("result")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(i)&nbsp; &nbsp; &nbsp; &nbsp; case <-time.After(4000 * time.Millisecond):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("timed out")&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Go
我要回答