[Golang] Read Yes/No From Console


Read Yes/No (i.e., ask for user confirmation) from console in Golang (Go programming language).

Source code:

askforconfirm.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package main

import (
	"fmt"
	"strings"
)

func Ask4confirm() bool {
	var s string

	fmt.Printf("(y/N): ")
	_, err := fmt.Scan(&s)
	if err != nil {
		panic(err)
	}

	s = strings.TrimSpace(s)
	s = strings.ToLower(s)

	if s == "y" || s == "yes" {
		return true
	}
	return false
}

func main() {
	isConfirmed := Ask4confirm()
	if isConfirmed {
		fmt.Println("confirmed")
	} else {
		fmt.Println("not confirmed")
	}
}

Tested on: Ubuntu Linux 15.10, Go 1.6.1.


References:

[1]golang reading yes or no - Google search
[2]go - How to read input from console line? - Stack Overflow
[3]go - Reading an integer from standard input in golang - Stack Overflow
[4]go to lowercase - Google search