Home > Backend Development > Golang > How to Read from Standard Input (stdin) in Go?

How to Read from Standard Input (stdin) in Go?

Susan Sarandon
Release: 2024-12-17 07:40:24
Original
120 people have browsed it

How to Read from Standard Input (stdin) in Go?

How to Read from Initial stdin in Go

In Go, reading from the initial stdin of a program can be achieved using the os.Stdin interface. However, if there is no input in os.Stdin, the program will wait for input.

Solution:

The recommended approach is to use os.Stdin as it provides a simple and reliable method for reading from the original stdin. To use os.Stdin, simply call the io.ReadAll() function to read all the bytes from the input.

Here's an example:

package main

import "os"
import "log"
import "io"

func main() {
    bytes, err := io.ReadAll(os.Stdin)

    log.Println(err, string(bytes))
}
Copy after login

When executed with echo test stdin | go run stdin.go, this code will print test stdin.

For line-based reading, the bufio.Scanner can be used:

import "os"
import "log"
import "bufio"

func main() {
    s := bufio.NewScanner(os.Stdin)
    for s.Scan() {
        log.Println("line", s.Text())
    }
}
Copy after login

The above is the detailed content of How to Read from Standard Input (stdin) in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template