1. Introduction
Functions are a very useful function provided by the Go standard library, which can specify the minimum number of bytes to be read from a data source. This article we will
Starting from the basic definition of the function, it describes its basic usage and implementation principles, as well as some precautions, and completes the
Introduction to functions.
2. Basic instructions
2.1 Basic definition
Functions are used to reader (
) Read at least a specified number of bytes into the buffer. The function definition is as follows:
func ReadAtLeast(r Reader, buf []byte, min int) (n int, err error)
inr
is the data source, read data from it, andbuf
is a byte slice used to receive the read data.min
is the minimum number of bytes to be read.The function will try to read at least from the reader
min
bytes of data and store it inbuf
middle.
2.2 Use examples
Below is a sample code that demonstrates how to use itThe function reads at least 5 bytes of data from standard input:
package main import ( "fmt" "io" "os" ) func main() { buffer := make([]byte, 10) n, err := (, buffer, 5) if err != nil { ("An error occurred during reading:", err) return } ("Read %d bytes successfully: %s\n", n, buffer) }
In this example, we create a byte slice of length 10buffer
, and useThe function reads at least 5 bytes of data from standard input to
buffer
middle. Here is a possible output, as follows:
hello,world Read successfully 10 Bytes:hello,worl
Here its specificationmin
is 5, which means at least 5 bytes of data is read, and then it is calledThe function reads 10 bytes of data at one time, and the requirements are also met at this time. It is also explained indirectly here
Only guarantee the minimum reading
min
bytes of data, but does not limit the reading of more data.
3. Implementation principle
UnderstandAfter the basic definition and use of the function, we will check it here
Function implementation is used to provide basic explanations and deepen the
Understanding of functions.
actuallyThe implementation is very simple, which defines a variable
n
, saves the number of bytes read, and then continuously calls the data source ReaderRead
Methods read data and then increase variablesn
value untiln
Greater than the minimum number of read bytes. Let's see the implementation of the specific code:
func ReadAtLeast(r Reader, buf []byte, min int) (n int, err error) { // The length of the incoming buffer buf is less than the minimum number of read bytes min, and the error is directly returned at this time if len(buf) &lt; min { return 0, ErrShortBuffer } // When n < min, the Read method is constantly called to read the data // Read up to len(buf) bytes of data for n &lt; min &amp;&amp; err == nil { var nn int nn, err = (buf[n:]) // Increase the value of n n += nn } if n &gt;= min { err = nil } else if n &gt; 0 &amp;&amp; err == EOF { // The number of data bytes read is less than the min value, and all the data has been read. Then ErrUnexpectedEOF is returned err = ErrUnexpectedEOF } return }
4. Things to note
4.1 Pay attention to the occurrence of infinite waiting situations
From aboveThe implementation can be seen that if no specified amount of data is read and no error occurs, it will wait until at least the specified amount of byte data is read, or an error is encountered. Here is a code example to show the following effect:
func main() { buffer := make([]byte, 5) n, err := (, buffer, 5) if err != nil { ("An error occurred during reading:", err) return } ("Read %d bytes successfully: %s\n", n, buffer) }
In the above code example, the callThe function reads 5 bytes of data from the standard input. If the standard input has not entered enough 5 bytes, the function will wait for it. For example, the following input is first entered
he
Two characters, then enter. Since 5 characters have not been reached yet, at this timeThe function will not return, only input it
llo
After these few characters, only 5 characters can be satisfied and the execution can be continued, soWhen functioning, you need to pay attention to infinite waiting.
he llo Read successfully 5 Bytes:he ll
4.2 Ensurebuf
The size is sufficient to accommodate at leastmin
Bytes of data
CallingWhen functioning, the buffer needs to be guaranteed
buf
The size needs to be metmin
, if the buffer size is greater thanmin
If the parameters are still small, they will never be satisfied at this time. At least readmin
Requirements for one byte of data.
From aboveThe implementation can be seen if it is found
buf
The length is less thanmin
, it will not try to read the data, it will directly return aErrShortBuffer
The error, the following is a code to show the effect:
func main() { buffer := make([]byte, 3) n, err := (, buffer, 5) if err != nil { ("An error occurred during reading:", err) return } ("Read %d bytes successfully: %s\n", n, buffer) }
For example, in the above function, the specifiedbuffer
The length is 3, butIt is required to read at least 5 bytes, at this time
buffer
It cannot accommodate 5 bytes of data, and it will be directlyErrShortBuffer
Error, as follows:
An error occurred during reading: short buffer
5. Summary
Functions are a tool function provided by the Go language standard library, which can read at least a specified amount of bytes of data from a data source into a buffer. Let's start with
Starting from the basic definition of the function, then use a simple example to show how to use it
Function implementation reads at least the specified byte data.
Then we talk about itThe implementation principle of the function is actually to continuously call the Read method of the source Reader, and the number of data read directly meets the requirements.
In terms of precautions, the call is emphasizedThere may be problems with infinite waiting and the need to ensure
buf
The size is sufficient to accommodate at leastmin
bytes of data.
Based on this, theI hope the introduction of functions will be helpful to you.
This is the end of this article about understanding functions. For more related function content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!