This is a creation in Article, where the information may have evolved or changed.
Go Bible-Learn notes Getting started Bufio.scanner
Bufio Reader and writer in the standard library, preferably for file IO operations, the data is cached in memory, and then the overall file IO operation, the maximum possible reduction of disk IO, but the size of the memory buffer is reasonable to set, the default size is 4,096 bytes.
Bufio. Writer use
List of methods provided by writer in the Bufio standard library
type Writer struct { err error buf []byte n int wr io.Writer}// 实例化bufio.Writer, 实例化是会直接分配大小为len(w.buf)大小的内存空间,Writer.n表示内存缓冲区已经存放的字节大小func NewWriter(w io.Writer) *Writerfunc NewWriterSize(w io.Writer, size int) *Writer// 表示可用的内存缓冲区大小len(b.buf)-nfunc (b *Writer) Avaliable() int// 表示已使用的内存缓冲区大小b.nfunc (b *Writer) Buffered() int// 这个首字母大写,表示用户可以手动触发内存缓冲区的数据,回写到wr.Write所指定的地方,一般为磁盘IO回写func (b *Writer) Flush() error// bufio.Writer把数据写到缓冲区挺有意思的。// 开发者可以阅读源码了解一下。我举第二个方法Write([]byte)func (b *Writer) ReadFrom(r io.Reader) (int64, error)func (b *Writer) Write(p []byte) (int, error)func (b *Writer) WriteByte(c byte) errorfunc (b *Writer) WriteRune(r rune) (int, error)func (b *Writer) WriteString(s string) (int, error)
func (b *Writer) Write(p []byte) (int, error)the correct understanding of the method:
- If the memory buffer has less space left than Len (p), it is discussed in two ways:
- If the current memory buffer is empty, write p data directly to disk Io,b.wr.write (p);
- If the current memory buffer is not empty, then the buffer is filled first, then the memory buffer data first disk IO writeback operation, then the memory buffer available size is len (writer.buf) length, then there are two kinds of situations discussed:
第一种:如果剩余要处理的p数据小于内存缓冲区的大小, 则把剩余数据p写入到内存缓冲区;第二种:如果剩余要处理的p数据大于等于内存缓冲区,则没必要缓冲了,直接整体一次回写到磁盘 .
- If the memory buffer space is greater than or equal to Len (p), the data is staged to the buffer first, reducing disk IO.
Summary: Bufio reader and writer operations generally apply to disk IO read-write scenarios. At the same time understand the implementation of the standard library, you can improve their programming thinking. The standard library Bufio is really interesting to write.