Wrap io.Reader or io.Writer with bufio.NewReader or bufio.NewWriter to buffer data and reduce system calls for efficient I/O.
Use bufio.NewReader to wrap an io.Reader for efficient reading or bufio.NewWriter to wrap an io.Writer for efficient writing. This reduces the number of system calls by buffering data in memory before processing.
import "bufio"
// Reading
reader := bufio.NewReader(os.Stdin)
line, err := reader.ReadString('\n')
// Writing
writer := bufio.NewWriter(os.Stdout)
writer.WriteString("Hello, world!\n")
writer.Flush() // Required to write buffered data
The bufio package adds a temporary holding area (buffer) between your program and the data source, like a file or network connection. Instead of asking for data one tiny piece at a time, which is slow, it grabs a big chunk and lets your program read from that chunk quickly. You use it whenever you are reading or writing files, network streams, or standard input to make your program run faster.