Search⌘ K

Scanning Inputs

Explore how to read user input in Go with the bufio Scanner, including scanning text until ENTER is pressed and customizing input splitting by characters, words, or alphanumeric tokens. Understand how to implement custom split functions and process input efficiently to handle various data tokenization needs.

We'll cover the following...

We already saw how to read from input. Another way to get input is by using the Scanner type from the bufio package:

package main
import (
"bufio"
"fmt"
"os"
)

func main() {
  scanner := bufio.NewScanner(os.Stdin)
  fmt.Println("Please enters some input: ")
  if scanner.Scan() {
    fmt.Println("The input was", scanner.Text())
  }
}

Click the RUN button, and wait for the terminal to start. Type go run main.go and press ENTER.

At line 9, we construct a Scanner instance from package bufio with input coming from the keyboard (os.Stdin). At line 11, scanner.Scan() takes any input (until ENTER key is pressed) and stores it into its Text() property, which is printed out at line 12. Scan() returns true when it gets input, and returns false when the scan stops, either by reaching the end of the input or an error. So, at the end of input, the if-statement is finished.

After the prompt "Please enter some input: ", ...