Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

How to Pause a Go Program until enter key is pressed

Posted on December 10, 2019December 10, 2019 by admin

Sometimes there is a need to pause a go program until a key is pressed. Eg. One would only want a go program to exit at the end only on the press of Enter key.

Below program will print the increasing and will stop as soon as you press the key is pressed. Try it out.

package main

import (
    "fmt"
    "time"
)

func main() {
    go counter()
    fmt.Println("Press the Enter Key to stop anytime")
    fmt.Scanln()
}

func counter() {
    i := 0
    for {
        fmt.Println(i)
        time.Sleep(time.Second * 1)
        i++
    }
}
Follow @golangbyexample

Popular Articles

Golang Comprehensive Tutorial Series

All Design Patterns in Go (Golang)

Slice in golang

Variables in Go (Golang) – Complete Guide

OOP: Inheritance in GOLANG complete guide

Using Context Package in GO (Golang) – Complete Guide

All data types in Golang with examples

Understanding time and date in Go (Golang) – Complete Guide

©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme