Go ( Golang) - Read Input from User or Console

In this tutorial, we will learn different ways to read input from the User or Console in the Golang program.

Go ( Golang) - Read Input from User or Console

We will see three different ways to read input from the User or Console in the Golang program.
  1. Go - read input with Scanf
  2. Go - read input from the user with NewReader
  3. Go - read input from the user with NewScanner

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.

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

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.

Below example read input from a user with NewScanner in the Go language.

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.

Golang Related Tutorials

Comments