๐ŸŽ“ A1Learner
๐Ÿ”

Go User Input

User input is data that a person types while a program runs. The fmt.Scan function reads that typed data into variables.

Reading one word

The prompt prints first with no new line. Scan then stores the typed word in name.

package main

import "fmt"

func main() {
	var name string
	fmt.Print("Your name: ")
	fmt.Scan(&name)
	fmt.Println("Hello,", name)
}

Reading two numbers

One Scan call can read two values. Each value goes into its own variable.

package main

import "fmt"

func main() {
	var a int
	var b int
	fmt.Print("Enter two numbers: ")
	fmt.Scan(&a, &b)
	fmt.Println("Sum:", a+b)
}

Reading a word and a number

Scan fills the variables in the order listed. The word goes into name and the number goes into age.

package main

import "fmt"

func main() {
	var name string
	var age int
	fmt.Print("Name and age: ")
	fmt.Scan(&name, &age)
	fmt.Println(name, "is", age)
}

Example

package main

import "fmt"

func main() {
	var item string
	var quantity int
	fmt.Print("Item and quantity: ")
	fmt.Scan(&item, &quantity)
	fmt.Println("Order:", quantity, "x", item)
}

Key points

  • Use fmt.Scan to read typed values into variables.
  • Scan reads one value for each variable it is given.
  • Scan reads values in order, split by spaces.
  • The & sign before a variable gives Scan the address of the variable.
  • Scan needs the address of the variable so it can store what is typed.
  • Use fmt.Print for a prompt so the next print stays on the same line.

In this example, the prompt prints with no new line. Scan stores the first typed word in item. Scan stores the number after it in quantity. The last print builds one line from both values.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

Why does fmt.Scan take &name instead of name?