How to take user input in Golang

In this shot, we will learn how to take user input in Golang.

Golang has a function called Scanln that is provided by the fmt package and used to take input from the user.

Syntax

  1. To take input from the same line, we will use the following syntax:
fmt.Scan(&variablename)
  1. To take input from a new line, we will use the following syntax:
fmt.Scanln(&variablename)

Where:

  • fmt is the package name
  • Scan or Scanln is the function that takes input
  • &variablename is the reference to the variable where we need to store the user input

In the example below, we take the user’s age as input and display a simple statement. We can perform any operation on the user input, such as sending it to the server when the user submits their form.

Code

package main
//import fmt package
import(
"fmt"
)
//program execution starts here
func main(){
//Display what you want from user
fmt.Println("Enter your age: ")
//Declare variable to store input
var age int
//Take input from user
fmt.Scanln(&age)
//Display age with statement
fmt.Println("You are ",age," years old.")
}

Enter the input below

Explanation

  • Line 5: Import the fmt package.
  • Line 9: The execution of program starts from the main() function.
  • Line 12: Display a statement or question to the user for which we take input.
  • Line 15: Declare a variable age of type int to store the input.
  • Line 18: Take input from the user with the Scanln function and pass the age variable as the parameter. When the user enters input, it will be stored in the age variable.
  • Line 21: Print a statement.

Free Resources