Read from stdin in Go using bufio.NewScanner(os.Stdin) to process input line-by-line.
Use bufio.NewScanner(os.Stdin) to read input line-by-line from standard input.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
}
}
Reading from stdin in Go creates a scanner that reads text from the keyboard or a pipe one line at a time. It loops through each line you type until you signal the end of input (usually by pressing Ctrl+D on Mac/Linux or Ctrl+Z on Windows). Think of it like a conveyor belt that picks up each line of text you provide and hands it to your program to process.