...

/

Scanning Inputs

Scanning Inputs

This lesson introduces a new method of reading input from the user, i.e., scanning the data from the user.

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 ...