Home >Backend Development >Golang >Can Go Access the Initial Standard Input Stream?

Can Go Access the Initial Standard Input Stream?

Susan Sarandon
Susan SarandonOriginal
2024-12-18 12:21:11779browse

Can Go Access the Initial Standard Input Stream?

In Go, Can You Access Initial Standard Input?

In Go, using os.Stdin to read from the original standard input should yield the desired results, as demonstrated by this code snippet:

package main

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

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

    log.Println(err, string(bytes))
}

When you execute echo test stdin | go run stdin.go, the program should print test stdin without issues.

If you encounter errors, providing the code you used will greatly help in identifying the problem.

For handling line-based input, you can utilize bufio.Scanner:

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

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

The above is the detailed content of Can Go Access the Initial Standard Input Stream?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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