golang can read keyboard input from the console. In this section you will learn how to do that..

To get keyboard input, first open a console to run your program in. Then it will ask for keyboard input and display whatever you’ve typed.

Related course:
Learn How To Code: Google’s Go (golang) Programming Language

Keyboard input in golang

Example

The golang program below gets keyboard input and saves it into a string variable. The string variable is then shown to the screen.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main

import (
"bufio"
"fmt"
"os"
)

func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter your city: ")
city, _ := reader.ReadString('\n')
fmt.Print("You live in " + city)
}

The data that we read from the console (keyboard), is stored in a variable and printed to the screen.
Sample output of program.

1
2
Enter city name: Sydney
You live in Sydney
This line will get keyboard input and store it in a variable:
1
2
3
4
5
# necessary
reader := bufio.NewReader(os.Stdin)

# read line from console
city, _ := reader.ReadString('\n')
You can get as many input variables as you want, simply by duplicating this line and changing the variable names.

Exercises

  1. Make a program that lets the user input a name
  2. Get a number from the console and check if it’s between 1 and 10.

Download Answers