2013-07-17 27 views
15

当我执行一个Go控制台程序时,它只执行一秒钟,我一直在Google,Go网站和Stackoverflow上查看。如何添加暂停到Go程序?

import (
    "fmt" 
) 

func main() { 
    fmt.Println() 
} 

它会立即关闭,当我执行它。

EDIT 2 其实我想要的程序,直到用户按下一个按钮

回答

36

您可以通过使用time.Sleep()暂停节目的任意长的时间长期居住暂停。例如:

package main 
import ("fmt" 
     "time" 
     ) 

func main() { 
    fmt.Println("Hello world!") 
    duration := time.Second 
    time.Sleep(duration) 
} 

为了增加持续时间随意,你可以这样做:

duration := time.Duration(10)*time.Second // Pause for 10 seconds 

编辑:由于OP增加了额外的约束,这个问题的答案上面不再符合本条例草案。您可以暂停,直到输入键通过创建一个等待读取换行符(\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') 
} 
+0

但这仅仅持续了几秒钟,我要当一个键被按下 – Vaderman2782

+1

@Vade程序退出rman2782你在问题中没有提到这一点。迈克应该如何知道? – Mostafa

+0

对不起。让我编辑它...... – Vaderman2782

2

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

var input string 
fmt.Scanln(&input) 

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

package main 

import "fmt" 

func main() { 
    fmt.Println("Press the Enter Key to terminate the console screen!") 
    var input string 
    fmt.Scanln(&input) 
} 
0
package main 

import "fmt" 

func main() { 
    fmt.Println("Press the Enter Key to terminate the console screen!") 
    fmt.Scanln() // wait for Enter Key 
} 
+0

@BalagurunathanMarimuthu代码中的单个注释是所有需要的解释。我发现更令人质疑的是,这只是Vas现有答案的简化版本而没有给出归因。 – Gimby

+0

Sory。我无法回答,因为声誉<50,我不知道英语) 评论...好的,但是在其他例子中,他们肯定需要的地方有很多评论吗? 我使用translater。 – mukexa