Go edit

Console I/O

When writing command-line programs, you can read user input from os.Stdin using any function that accepts io.Reader.

fmt.Scanf to read from stdio

Most convenient way is to use fmt.Scanf which is a mirror image of fmt.Printf.

Here's how to read a string and an integer from the console (standard input)

fmt.Print("What is your name?\n")
var name string
if n, err := fmt.Scanf("%s", &name); err != nil {
    fmt.Printf("fmt.Scanf failed with '%s'\n", err)
} else {
    fmt.Printf("fmt.Scanf scanned %d item(s) and set name to '%s'\n", n, name)
}
fmt.Print("What is your age?\n")
var age int
if n, err :=  fmt.Scanf("%d", &age); err != nil {
    fmt.Printf("fmt.Scanf failed with '%s'\n", err)
} else {
    fmt.Printf("fmt.Scanf scanned %d item(s) and set age to '%d'\n", n, age)
}

fmt.Scanf reads input from os.Stdin and tries to set passed variables based on provided format.

A space and newline are considered value separators.

It returns number of successfully parsed items (in case it only matched first few variables).

To read from arbitrary io.Reader use fmt.Fscanf.

fmt.Scanln to read a line from stdin

To read a full line (until newline or io.EOF, use fmt.Scanln:

var line string
fmt.Scanln(&line)
fmt.Printf("Entered line: '%s'\n", line)

bufio.Reader to read a line from stdin

You can also use bufio.Reader:

reader := bufio.NewReader(os.Stdin)
if line, err := reader.ReadString('\n'); err != nil {
    fmt.Printf("ReadString failed with '%s'\n", err)
} else {
    fmt.Printf("Entered line: '%s'\n", line)
}

ReadString reads from the reader until it reads a given character. We specified newline \n character so it'll read a full line.

The value returned by ReadString includes the terminating character (\n) so often you'll want to strip it with e.g. strings.TrimSpace.

Character \n is a line terminator on Unix. On Windows it's more common to see \r\n as a line terminator. If you expect to be run on Windows, make sure to handle this (e.g. by trimming \r character from returned string).

bufio.Scanner to read a line from stdi

You can also use bufio.Scanner to read lines from stdin

scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
    line := scanner.Text()
    fmt.Printf("Entered line: '%s'\n", line)
}

bufio.Scanner allows for more complicated use where you specify a function to split input in chunks with Scanner.Split.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:

  ↑ ↓ to navigate     ↵ to select     Esc to close