如何为Go程序添加暂停?

Vad*_*782 31 go

当我执行Go控制台程序时,它只在一秒内执行,我一直在谷歌,Go网站和Stackoverflow上查找.

import (
    "fmt"
)

func main() {
    fmt.Println()
}
Run Code Online (Sandbox Code Playgroud)

当我执行它时立即关闭.

编辑2实际上我希望程序永久保持暂停状态,直到用户按下按钮

小智 54

您可以使用以暂停程序任意长时间time.Sleep().例如:

package main
import ( "fmt"
         "time"
       )   

func main() {
  fmt.Println("Hello world!")
  duration := time.Second
  time.Sleep(duration)
}
Run Code Online (Sandbox Code Playgroud)

要随意增加持续时间,您可以:

duration := time.Duration(10)*time.Second // Pause for 10 seconds
Run Code Online (Sandbox Code Playgroud)

编辑:由于OP增加了对问题的额外限制,上面的答案不再适合该法案.您可以Enter通过创建一个等待读取换行符(\n)字符的新缓冲读取器来暂停直到按下该键.

package main
import ( "fmt"
         "bufio"
         "os"
       )

func main() {
  fmt.Println("Hello world!")
  fmt.Print("Press 'Enter' to continue...")
  bufio.NewReader(os.Stdin).ReadBytes('\n') 
}
Run Code Online (Sandbox Code Playgroud)

  • @ Vaderman2782添加了暂停的其他代码,直到按下Enter键. (7认同)
  • @Vaderman2782 你没有在问题中提到这一点。迈克应该怎么知道? (2认同)

小智 10

最简单的另一种最小进口方式使用这2行:

var input string
fmt.Scanln(&input)
Run Code Online (Sandbox Code Playgroud)

在程序结束时添加此行将暂停屏幕,直到用户按下Enter键,例如:

package main

import "fmt"

func main() {
    fmt.Println("Press the Enter Key to terminate the console screen!")
    var input string
    fmt.Scanln(&input)
}
Run Code Online (Sandbox Code Playgroud)


小智 9

package main

import "fmt"

func main() {
    fmt.Println("Press the Enter Key to terminate the console screen!")
    fmt.Scanln() // wait for Enter Key
}
Run Code Online (Sandbox Code Playgroud)

  • @BalagurunathanMarimuthu 代码中的单个注释就是所需的全部解释。我觉得更值得怀疑的是,这只是 Vas 现有答案的简化版本,没有给出归属。 (2认同)