You have to work really hard to look effortless!

Wechat search public number [long Coding road], together From Zero To Hero!

preface

IO operations are unavoidable in programming, such as reading and writing files. IO packages of Go language provide relevant interfaces and define corresponding specifications. Different data types can realize corresponding methods according to the specifications and provide richer functions.

The Go language advocates a combination of small interfaces and interfaces to extend the behavior and flexibility of programs. The IO code package is just such a benchmark, it can be a reference when we use this technique. The IO package contains a large number of interfaces. In this article, we will first learn four core interfaces and their corresponding interface combinations.

Reader

The IO.Reader interface defines the Read method, which reads data into a byte array:

  • Input parameter: byte array P, which reads data into P
  • Return value: the number of bytes read this time, n, and the error err encountered
type Reader interface {
	Read(p []byte) (n int, err error)
}
Copy the code

Methods Detailed explanation of functions

  1. Method reads data into the byte array p, which, since P is sized, reads at most len(p) bytes at a time
  2. Method returns the number of bytes of data read, n(0 <= n <= len(p)), and the error encountered during the read
  3. Even if a single call reads less than len(p), it may take up the entire byte array P as staging space
  4. If the data source has less than len(p) bytes, the method simply reads the currently available data and does not wait for more data to arrive

When to return error

  1. After n (n>0) bytes are read successfully, if an error is generated or the end of file is read, this call must return the number of bytes read. However, for the value of err, you can choose to return err (err! =nil), or return err (n=0, err! = nil). A common example is to read n bytes and reach the end of the file (EOF). At this point, we can return err=EOF or err=nil. The next call returns n=0,err=EOF.
  2. Callers need to be aware that after each call, if n>0, they should process the data first before considering whether err is nil. If an error is encountered after reading n>0 bytes, both n>0 and err! Are returned. =nil, in which case you need to deal with the data before you worry about err.

Method implementation and invocation need attention

  1. If you want to implement this method, it is not recommended to return both n=0 and err=nil unless Len (p)=0
  2. If this method returns n=0 and err=nil, nothing happened, not end-of-file.
  3. After implementing this method, do not hold the byte array p (save the address for other purposes)

Writer

The IO.Writer interface defines the Write method, which is used to Write data to files

  • Input parameter: byte array P, which writes data from P to a file
  • Return value: number of bytes successfully written, n, and error err encountered
type Writer interface {
	Write(p []byte) (n int, err error)
}
Copy the code

Methods Detailed explanation of functions

  1. This method writes the data in P to a file
  2. Method returns the number of bytes successfully written n(0 <= n <= len(p)) and the error err encountered during the write
  3. If n
  4. Methods must not modify the byte array p, even temporary modifications are not allowed

Method implementation needs attention

  1. When you implement this method, you must not hold the byte array P, just use it to read data

Closer

The IO.Closer interface defines the Close method, which is used to Close the connection.

Method implementation needs attention

The interface is undefined and depends on the implementation method to define what behavior should result from calling the method the first time.

type Closer interface {
	Close() error
}
Copy the code

Seeker

The IO.Seeker interface defines the Seek method, which specifies the offset for the next read or write

  • Input parameter: Calculate the starting value of the new offset whence, based on the offset of whence
  • Return value: new offset value calculated based on whence and offset, and possible errors
type Seeker interface {
	Seek(offset int64, whence int) (int64, error)
}
Copy the code

Methods Detailed explanation of functions

  1. The IO package defines the following three types whence

    const (
    	SeekStart   = 0 // Based on the start of the file
    	SeekCurrent = 1 // Based on current offset
    	SeekEnd     = 2 // Based on the end of the file
    )
    Copy the code
  2. If the new offset is computed before the start of the file, error! =nil

  3. Any positive offset is legal, but how do I/O operations on the data source depend on the implementation method

Composite interface

In go, a combination of interfaces can be used to include methods in other interfaces, similar to defining a single parent interface that can contain multiple subinterfaces. If a struct implements all the methods of its subinterfaces, it implements the parent interface. The combination of small interface and interface greatly increases the flexibility of the program, which can be used for reference in our own business development process.

For the four interfaces with the minimum granularity, the I/O package defines the following composite interfaces:

// ReadWriter is a combination of the Read and Write methods
type ReadWriter interface {
	Reader
	Writer
}

ReadCloser is a combination of the Read and Close methods
type ReadCloser interface {
	Reader
	Closer
}

// WriteCloser is a combination of Write and Close methods
type WriteCloser interface {
	Writer
	Closer
}

// ReadWriteCloser is a combination of Read, Write, and Close methods
type ReadWriteCloser interface {
	Reader
	Writer
	Closer
}

// ReadSeeker is a combination of the Read and Seek methods
type ReadSeeker interface {
	Reader
	Seeker
}

// WriteSeeker is a combination of Write and Seek methods
type WriteSeeker interface {
	Writer
	Seeker
}

// ReadWriteSeeker is a combination of Read, Write, and Seek methods
type ReadWriteSeeker interface {
	Reader
	Writer
	Seeker
}
Copy the code

conclusion

This article introduces the four core interfaces in the IO package:

  • Reader: Reads data from a file into a byte array
  • Writer: Writes the byte array data to a file
  • Closer: Closes the connection
  • Seeker: Given whence and offset, calculate the new offset to start reading and writing at a specific location

You can see that both the Reader and Writer interfaces define methods with a byte array P, and that the underlying files are not represented in the methods. The Read method reads data from a file into a byte array p, and the Write method writes data from a byte array P to a file.

More and more

Personal blog: lifelmy.github. IO /

Wechat official account: Long Coding road