This article analyzes the common interface of the go IO package. Share to everyone for your reference. The specific analysis is as follows:
I do not have C + + base, no interface concept, and from Python to come, Python minimalism (a result often only provides one method), let me be very confused in the Golang, especially the file read and write operation, because go file read and write operation there are many ways, Let me not know how to choose. Until I learned the concept of interface, and then by looking at package IO only slowly understand, but also gradually like the flexibility of the Golang. In my experience, interfaces are a very important point of knowledge, a specification of a range of operations, especially for public interfaces, such as: Package IO
This article only lists the most commonly used interfaces, if you would like to System learning IO interface, suggest reading the bottom reference link.
First, IO interface overview
The package OS provides a basic interface to the I/O primitives, making it a shared public interface that abstracts out the ubiquitous functions and attaches some primitive-related operations. Because these interfaces and primitives are wrappers for a completely different low-level operation on the bottom, the client should not assume that they are concurrent execution safe unless otherwise notified.
The most important of the package OS is two interfaces: Reader and Writer interfaces. The various interfaces mentioned in this chapter are related to these two interfaces, that is, as long as the two interfaces are implemented, it has IO functionality.
Tips:
var EOF = errors. New ("EOF"): Defined in package Io, used very frequently. Normally, when Read () cannot get more returns, it returns EOF, where the file arrives at the end (End-of-file).
Second, Io. Reader and IO. Writer
definition:
Copy Code code as follows:
Type Reader Interface {
Read (P []byte) (n int, err error)
}
Type Writer Interface {
Write (P []byte) (n int, err error)
}
Read reads Len (p) bytes into p and returns the number of bytes read immediately when any errors (including EOF) are encountered, and the end of the function returns the number of bytes that were read successfully and any errors.
Write writes Len (p) byte data from p to the underlying data stream, and then returns the number of bytes successfully written and any errors.
It's easy to guess from the interface name, generally, the naming convention for interfaces in go: interface names end With ER. Note that this is not a mandatory requirement, and you can end it without an ER at all. Some interfaces in the standard library do not end with ER.
Example:
Copy Code code as follows:
Func WR () {
F, _: = OS. Create ("At.txt")
Defer F.close ()
F.write ([]byte ("Go is a pleasant programming language")//write Byte stream
F.seek (0, OS. Seek_set)//Reset the pointer
P: = Make ([]byte, 2)//Read 2 byte (len (BUF) =2)
If _, Err: = F.read (P); Err!= Nil {
Log. Fatal ("[F]", err)
}
Fmt. Printf ("read character \%s\", Length%d byte\n ", p, Len (p))
p = Make ([]byte, 50)
If _, Err: = F.read (P); Err!= Nil {
If Err!= io. EOF {//Ignore EOF error
Log. Fatal ("[F]", err)
}
}
Fmt. Printf ("read character \%s\", Length%d byte\n ", p, Len (p))
}
Reads the character "go" for a length of 2 byte
Read character "is a pleasing programming language", Length of byte
Third, Io. Readerat and OS. Writerat
Definition (off is an abbreviation for offset):
Copy Code code as follows:
Type Readerat Interface {
ReadAt (p []byte, off Int64) (n int, err error)
}
Type Writerat Interface {
Writeat (p []byte, off Int64) (n int, err error)
}
ReadAt () starts at the offset off of the base input source, and the other is the same as Read ();
Writeat () starts at the offset from the base input source, and the other is the same as Write ().
Example:
Copy Code code as follows:
Func at () {
F, _: = OS. Create ("At.txt")
Defer F.close ()
F.writestring ("Go is a delightful programming language")
F.writeat ([]byte ("program"), 26)//Offset 26byte rewrite "programming"-> "program"
Fi, _: = F.stat ()//Get file information
P: = Make ([]byte, FI. Size ()-2)//File size minus offset value
F.readat (P, 2)//Offset 2 byte
Os. Stdout.write (P)
}
Four, Io. Readerfrom and OS. Writerto
Defined:
Copy Code code as follows:
Type Readerfrom Interface {
Readfrom (R Reader) (n Int64, err error)
}
Type Writerto Interface {
WriteTo (w Writer) (n Int64, err error)
}
Readfrom () reads the data from R until EOF or an error occurs. Returns the number of bytes read and IO. An error other than EOF. Readfrom does not return EOF error
WriteTo () writes data to W until no data is writable or an error occurs. Returns the number of bytes written and any errors.
Example:
Copy Code code as follows:
Func FromTo () {
r: = Strings. Newreader ("Go is a pleasing programming language")//Create a Reader
W: = Bufio. Newwriter (OS. Stdout)//Create a Writer
W.readfrom (R)//w Read all the contents of R at once
W.flush ()
R.seek (0, OS. Seek_set)//Reset pointer
R.writeto (w)//R writes content to W in a one-time
W.flush ()
}
Five, Io. Seeker
Defined:
Copy Code code as follows:
Type Seeker Interface {
Seek (offset int64, whence int) (ret int64, err Error)
}
Seek sets the offset for the next Read or Write, and its interpretation depends on the whence. See above for examples.
whence values, the corresponding constants are defined in the OS package:
Copy Code code as follows:
Seek_set int = 0//Set offset at start of file
seek_cur int = 1//Set offset from the current position of the file's pointer
seek_end int = 2//Set offset at end of file
six, Io. Closer
Defined:
Copy Code code as follows:
Type Closer Interface {
Close () error
}
To turn off the data stream and release the resources, no more nonsense.
Vii. Other
Copy Code code as follows:
Type Bytereader Interface {
ReadByte () (c byte, err error)
}
Type Runereader Interface {
Readrune () (R rune, size int, err error)
}
ReadByte reads a single byte from the input and returns. If there is no byte to read, an error is returned.
Readrune reads a single UTF-8 encoded character, returning the character and its byte length. If no valid characters are available, an error is returned.
Copy Code code as follows:
Type Bytewriter Interface {
WriteByte (c byte) error
}
WriteByte writes a byte and returns an error if the write fails.
Reference:
Https://gowalker.org/io
Https://github.com/polaris1119/The-Golang-Standard-Library-by-Example/blob/master/chapter01/01.1.md
I hope this article will help you with your go language program.