SoFunction
Updated on 2025-03-01

Basic usage and principle analysis of functions in Go language

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 willStarting from the basic definition of the function, it describes its basic usage and implementation principles, as well as some precautions, and completes theIntroduction 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)

inris the data source, read data from it, andbufis a byte slice used to receive the read data.minis the minimum number of bytes to be read.The function will try to read at least from the readerminbytes of data and store it inbufmiddle.

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 tobuffermiddle. Here is a possible output, as follows:

hello,world
Read successfully 10 Bytes:hello,worl

Here its specificationminis 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 hereOnly guarantee the minimum readingminbytes 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 hereFunction implementation is used to provide basic explanations and deepen theUnderstanding of functions.

actuallyThe implementation is very simple, which defines a variablen, saves the number of bytes read, and then continuously calls the data source ReaderReadMethods read data and then increase variablesnvalue untilnGreater 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) < 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 < min && err == nil {
      var nn int
      nn, err = (buf[n:])
      // Increase the value of n      n += nn
   }
   if n >= min {
      err = nil
   } else if n > 0 && 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 enteredheTwo characters, then enter. Since 5 characters have not been reached yet, at this timeThe function will not return, only input itlloAfter 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 EnsurebufThe size is sufficient to accommodate at leastminBytes of data

CallingWhen functioning, the buffer needs to be guaranteedbufThe size needs to be metmin, if the buffer size is greater thanminIf the parameters are still small, they will never be satisfied at this time. At least readminRequirements for one byte of data.

From aboveThe implementation can be seen if it is foundbufThe length is less thanmin, it will not try to read the data, it will directly return aErrShortBufferThe 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 specifiedbufferThe length is 3, butIt is required to read at least 5 bytes, at this timebufferIt cannot accommodate 5 bytes of data, and it will be directlyErrShortBufferError, 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 withStarting from the basic definition of the function, then use a simple example to show how to use itFunction 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 ensurebufThe size is sufficient to accommodate at leastminbytes 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!