Use bufio.NewReader and bufio.NewWriter to wrap I/O streams for efficient buffered reading and writing in Go.
Use bufio.NewReader to wrap an io.Reader for efficient buffered reading and bufio.NewWriter to wrap an io.Writer for buffered writing.
import "bufio"
// Buffered reading
reader := bufio.NewReader(os.Stdin)
line, err := reader.ReadString('\n')
// Buffered writing
writer := bufio.NewWriter(os.Stdout)
writer.WriteString("Hello, world!\n")
writer.Flush() // Required to flush data to the underlying writer
The bufio package adds a temporary storage area (buffer) between your program and the data source or destination. This reduces the number of slow system calls by reading or writing data in larger chunks at once. Think of it like using a bucket to carry water instead of a spoon; you make fewer trips to get the same amount done.