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条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制