How to Read User Input Using Go
Just like printing to the console, reading input from the console with Go is very straightforward. This post aims to teach you just that by going through the steps on how to create a script that outputs 'Hello {name}', where {name} is provided by user input.
To read user input, Go uses a function called 'Scan()', which can be found in the 'fmt' package, so we need to import it. Assuming the code will reside in the function 'main', we get the following starter code:
package main
import "fmt"
func main() {
// write code here
}
In the main function, we first want to declare a string variable that will store the user's input. We can call this variable 'firstName'.
package main
import "fmt"
func main() {
var firstName string
}
We can then use the 'Scan()' function to get the user input and store it into the 'firstName' variable. It is important to understand that 'Scan()' takes in a pointer to a variable. This is because Go needs the memory address of the variable in order to assign it a value. Therefore, we write '&firstName' as the parameter.
package main
import "fmt"
func main() {
var firstName string
fmt.Scan(&firstName)
}
Lastly, we want to output a greeting to the screen. We can do this with the 'Println()' function. Note that this function is the exact same as 'Print()' but it adds a newline character to the end of the outputted string.
package main
import "fmt"
func main() {
var firstName string
fmt.Scan(&firstName)
fmt.Println("Hello", firstName)
}
With the script finished, you can run it with 'go run main.go'.
Subscribe to my newsletter
Read articles from Alissa Lozhkin directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Alissa Lozhkin
Alissa Lozhkin
My name is Alissa and I am a fourth-year computer science and math student at the University of Toronto! I am very interested in computer science and software development, and I love learning about new technologies! Get in touch with me on LinkedIn: https://www.linkedin.com/in/alissa-lozhkin