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
- To take input from the same line, we will use the following syntax:
fmt.Scan(&variablename)
- To take input from a new line, we will use the following syntax:
fmt.Scanln(&variablename)
Where:
fmtis the package nameScanorScanlnis the function that takes input&variablenameis 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 packageimport("fmt")//program execution starts herefunc main(){//Display what you want from userfmt.Println("Enter your age: ")//Declare variable to store inputvar age int//Take input from userfmt.Scanln(&age)//Display age with statementfmt.Println("You are ",age," years old.")}
Enter the input below
Explanation
- Line 5: Import the
fmtpackage. - 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
ageof typeintto store the input. - Line 18: Take input from the user with the
Scanlnfunction and pass theagevariable as the parameter. When the user enters input, it will be stored in theagevariable. - Line 21: Print a statement.