Go Input
What is Input?
In this tutorial, we will be discussing Go functions which you can use to input stuff into your program, specifically command line input.
The Scan()
function
The Scan()
function, as well as all the other functions we will be discussing in this tutorial, is in the built-in fmt
module, so we need to type import "fmt"
before using these functions, as always.
The Scan()
function receives raw user input as space-seperated values and stores them in variables. Newlines count as spaces. For example:
package main
import "fmt"
func main() {
var fname string
var lname string
fmt.Println("Enter Your Name: ")
fmt.Scan(&fname)
fmt.Scan(&lname)
fmt.Println("Your First Name Is", fname)
fmt.Println("Your Last Name Is", lname)
}
By running this code in the command line, we get a simple program that asks you for your name. Try entering a first name and a last name, seperated by spaces, like "John Doe
" and then the program prints out your name:
Your First Name Is John Your Last Name Is Doe
The Scanln()
function
The Scanln()
function is like Scan()
, but it stops scanning for inputs at newlines. For example:
The Scanf()
function
The Scanf()
function is similar to the Printf()
function. The Scanf()
function uses a pre-defined format for the input and stores in the variables.