dsfhe34889789708 2018-06-11 12:17
浏览 133
已采纳

超时后如何取消fmt.Scanf?

I have a very simple command line utility and at the end of it I'm waiting for a user to hit the enter key to end the program:

fmt.Scanf("
") // wait for hitting the enter key to end the program

Now I want to change it and if the enter key hasn't been hit for some time, I want to cancel Scanf and do something else. Is it possible to cancel waiting for user's input?

  • 写回答

2条回答 默认 最新

  • drug95107 2018-06-11 13:04
    关注

    You can simply create a channel and launch a goroutine which does the fmt.Scanf(" ") and then writes something to the channel. Then select between that channel and time.After(3 * time.Second).

    Here's a clean solution:

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        // Rest of the program...
    
        ch := make(chan int)
    
        go func() {
            fmt.Scanf("
    ")
            ch <- 1
        }()
    
        select {
        case <-ch:
            fmt.Println("Exiting.")
        case <-time.After(3 * time.Second):
            fmt.Println("Timed out, exiting.")
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面