Tutorials References Exercises Menu
Paid Courses

Go User Input


Go User Input

Go has multiple ways to receive inputs from the user.

In this chapter you will learn about the following functions:

  • Scan()
  • Scanln()
  • Scanf()

The Scan() Function

The Scan() function receives the user input in raw format as space-separated values and stores them in the variables. Newlines count as spaces.

Example

This example receives the value of i and prints it:

package main
import ("fmt")

func main() {
  var i int

  fmt.Print("Type a number: ")
  fmt.Scan(&i)
  fmt.Println("Your number is:", i)
}
Try it Yourself »

You can have more than one user input.

Example

This example receives the values of i and j and prints them:

package main
import ("fmt")

func main() {
  var i,j int

  fmt.Print("Type two numbers: ")
  fmt.Scan(&i, &j)
  fmt.Println("Your numbers are:", i, "and", j)
}
Try it Yourself »

Note: &i and &j are memory locations of i and j.


The Scanln() Function

The Scanln() function is similar to Scan(), but it stops scanning for inputs at a newline (at the press of the Enter key.).

Example

This example receives the values of i and j and then prints them:

package main
import ("fmt")

func main() {
  var i,j int

  fmt.Print("Type two numbers: ")
  fmt.Scanln(&i, &j)
  fmt.Println("Your numbers are:", i, "and", j)
}
Try it Yourself »

The Scanf() Function

The Scanf() function receives the inputs and stores them based on the determined formats for its arguments.

Example

This example receives the values of i and j and then prints them:

package main
import ("fmt")

func main() {
  var i,j int

  fmt.Print("Type two numbers: ")
  fmt.Scanf("%v %v",&i, &j)
  fmt.Println("Your numbers are:", i, "and", j)
}
Try it Yourself »

Example Explained

In this example, the inputs are received in exactly the same way defined in Scanf() formatting.

This means that the code expects inputs to be received with one space between them. Like: 1 2.

Note: %v tells Scanf() to store the value of the inputs in the variables.

It is possible to edit the code from example above to have different receiving formats.

Example

This example receives the values of i and j in separate lines and then prints them:

package main
import ("fmt")

func main() {
  var i,j int

  fmt.Print("Type two numbers: ")
  fmt.Scanf("%v\n%v",&i, &j)
  fmt.Println("Your numbers are:", i, "and", j)
}
Try it Yourself »