Go – Read String Input from Console
In this tutorial, we will learn how to read a string input from the console in the Go programming language (Golang). Reading input from the console is a common operation for interactive programs.
We’ll explore a simple way to accomplish this using the fmt.Scanln
function, along with a detailed explanation and examples.
Syntax to Read String Input
The basic syntax to read a string input in Go is:
fmt.Scanln(&variable)
Here, variable
is the string variable where the input from the console will be stored.
The ampersand (&
) is used to pass the memory address of the variable to the Scanln
function.
Example Program to Read String Input
In this example, we prompt user to input a string, read the string using Scanln(), and finally print the read string to output.
Program – example.go
package main
import "fmt"
func main() {
// Declare a string variable to hold user input
var input string
// Prompt the user
fmt.Print("Enter a string: ")
// Read input from the console
fmt.Scanln(&input)
// Print the input back to the console
fmt.Println("You entered:", input)
}
Explanation of Program
- Declare a Variable: A variable of type
string
is declared to store the user input. - Prompt the User: The
fmt.Print
function is used to display a message prompting the user to enter a string. - Read the Input: The
fmt.Scanln
function reads the input typed by the user and stores it in the variable. The&
operator is used to pass the address of the variable. - Print the Input: The entered string is printed back to the console using the
fmt.Println
function.
Output
This example demonstrates how to read a single string input from the user via the console and display it back.
Handling Multiple Words
The fmt.Scanln
function reads input up to the first whitespace. If you need to read an entire line, including spaces, you can use the bufio
package:
Program – example.go
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
// Create a reader to read input
reader := bufio.NewReader(os.Stdin)
// Prompt the user
fmt.Print("Enter a full line: ")
// Read the full line of input
input, _ := reader.ReadString('\n')
// Print the input back to the console
fmt.Println("You entered:", input)
}
Output
The bufio.NewReader
with ReadString
is useful for reading input containing spaces or special characters.