In this tutorial, you will learn different ways to get input from User in Go Lang with examples.
To read input from users in Go, we use the fmt, bufio, and os packages.1. Go read input with Scanf
The Scanf function scans text read from standard input, storing successive space-separated values into successive arguments as determined by the format. It returns the number of items successfully scanned.
Let's create a file named go_example.go and add the following content to it:
package main
import "fmt"
func main() {
var name string
fmt.Print("Enter your name: ")
fmt.Scanf("%s", &name)
fmt.Println("Hello", name)
}
Output:
G:\GoLang\examples>go run go_example.go Enter your name: John Hello John
The example prompts the user to enter his name.
2. Go read input from the user with NewReader
The program reads a name from the input using bufio.NewReader.
Let's create a file named go_example.go and add the following content to it:
package main
import (
"os"
"bufio"
"fmt"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter your name: ")
name, _ := reader.ReadString('\n')
fmt.Printf("Hello %s\n", name)
}
Output:
G:\GoLang\examples>go run go_example.go Enter your name: John Hello John
3. Go read input from the user with NewScanner
The Scanner provides a convenient interface for reading data such as a file of newline-delimited lines of text.
Let's create a file named go_example.go and add the following content to it:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
names := make([]string, 0)
scanner := bufio.NewScanner(os.Stdin)
for {
fmt.Print("Enter name: ")
scanner.Scan()
text := scanner.Text()
if len(text) != 0 {
fmt.Println(text)
names = append(names, text)
} else {
break
}
}
fmt.Println(names)
}
Output:
G:\GoLang\examples>go run go_example.go Enter name: John John Enter name: Tony Tony Enter name: Tom Tom Enter name: [John Tony Tom]
Note: The example allows to read multiple names from the user. Press enter without value to finish the program.
Free Spring Boot Tutorial - 5 Hours Full Course
Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course