How to add pause to a Go program?

package main

import "fmt"

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

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

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') 
}

Tags:

Go