Go · Stage 2 – Doing Things with Values · Lesson 18 of 64

Getting User Input

Read a small value typed by the user.

fmt.Scan can read one space-separated value from the terminal.

Go code

var name string
fmt.Print("Name: ")
fmt.Scan(&name)
fmt.Println("Hello", name)
Line-by-line explanation
  1. A string variable is declared.
  2. Print displays a prompt without a new line.
  3. Scan reads into name; the ampersand supplies its address.
  4. Println displays the greeting.
Expected output
Name: Maya
Hello Maya

The user typed Maya after the prompt. Pointers are explained slowly in Stage 7.

For full lines containing spaces, a bufio.Scanner is more suitable and will be introduced when file and input handling are deeper.