How to Add Pause to a Go Program?

How to Add Pause to a Go Program?

When i ever execute a Go Console program it just executes in one second, I've been looking on Google, the Go website and Stackoverflow.

import (
    "fmt"
)

func main() {
    fmt.Println()
}

It closes immediately when i execute it.

EDIT 2 actually i wanted the program to permanently stay paused untill the user presses a button

4 Answers

You can pause the program for an arbitrarily long time by using time.Sleep(). For example:

package main
import ( "fmt"
         "time"
       )   

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

To increase the duration arbitrarily you can do:

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

EDIT: Since the OP added additional constraints to the question the answer above no longer fits the bill. You can pause until the Enter key is pressed by creating a new buffer reader which waits to read the newline (\n) character.

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

func main() {
  fmt.Println("Hello world!")
  fmt.Print("Press 'Enter' to continue...")
  bufio.NewReader(os.Stdin).ReadBytes('\n') 
}
4
package main

import "fmt"

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

The easiest another way with minimal imports use this 2 lines :

var input string
fmt.Scanln(&input)

Adding this line at the end of the program, will pause the screen until user press the Enter Key, for example:

package main

import "fmt"

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

func main() {
    fmt.Scanln()
}

I use fmt.Scanln just one line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.