ZetCode

Go read input

last modified April 11, 2024

In this article we show how to read input from a user. Standard input, often abbreviated stdin, is a stream from which a program reads its input data.

To read input from users in Go, we use the fmt, bufio, and os packages.

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.

read_input.go
package main

import "fmt"

func main() {

    var name string

    fmt.Print("Enter your name: ")
    fmt.Scanf("%s", &name)
    fmt.Println("Hello", name)
}

The example prompts the user to enter his name.

var name string

We define a string variable.

fmt.Scanf("%s", &name)

The entered value is stored into the name variable.

$ go run read_input.go 
Enter your name: Peter
Hello Peter

We run the program and enter a name.

In the next example, we read two values.

read_input2.go
package main

import "fmt"

func main() {

    var name string
    var age int

    fmt.Print("Enter your name & age: ")
    fmt.Scanf("%s %d", &name, &age)
    fmt.Printf("%s is %d years old\n", name, age)
}

The program reads a name and age from the user.

fmt.Scanf("%s %d", &name, &age)

The Scanf function reads a string and an integer to the two provided variables.

$ go run read_input2.go 
Enter your name & age: Peter 34
Peter is 34 years old

Go read input with NewReader

The bufio package implements buffered I/O. Buffered I/O has much better performance than non-buffered. The package wraps an io.Reader or io.Writer object, creating another object (Reader or Writer) that also implements the interface but provides buffering and some help for textual I/O.

read_input3.go
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)
}

The program reads a name from the input using bufio.NewReader.

reader := bufio.NewReader(os.Stdin)

We pass the standard input to the bufio.NewReader.

name, _ := reader.ReadString('\n')

The ReadString reads until the first occurrence of the specified delimiter (new-line in our case) in the input, returning a string containing the data up to and including the delimiter.

Go read input with NewScanner

The Scanner provides a convenient interface for reading data such as a file of newline-delimited lines of text.

read_input4.go
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)
}

The example allows to read multiple names from the user. Press enter without value to finish the program.

names := make([]string, 0)

We create an empty slice.

scanner := bufio.NewScanner(os.Stdin)

A new scanner is created from the standard input.

for {
     fmt.Print("Enter name: ")
...

In a for loop, we repeatedly ask the user for a name.

scanner.Scan()

We read a line from standard input. The Scan advances the Scanner to the next token, which will then be available through the Bytes or Text function.

text := scanner.Text()

The Text returns the most recent token generated by a call to Scan as a newly allocated string holding its bytes.

if len(text) != 0 {

     fmt.Println(text)
     names = append(names, text)
} else {
     break
}

If the text is not empty, we print it and append it to the slice.

fmt.Println(names)

Finally, we print all the scanned names.

$ go run read_input3.go 
Enter name: Lucia
Lucia
Enter name: Peter
Peter
Enter name: Roman     
Roman
Enter name: Jane
Jane
Enter name: [Lucia Peter Roman Jane]

Source

Go bufio package - reference

In this article we have covered ways to read input from a user in Golang.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Go tutorials.