io.ReadAtLeast() Function in Golang with Examples
In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The ReadAtLeast() function in Go language is used to read from the stated reader “r” into the stated buffer “buf” until it has read for at least the minimum number of stated bytes. Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions.
func ReadAtLeast(r Reader, buf byte, min int) (n int, err error)
Here, “r” is the reader stated, “buf” is the buffer stated, and “min” is the minimum number of bytes until which the reader reads into the given buffer.
Return value: It returns the number of bytes that the stated buffer copies and also returns an error if the number of bytes reads are less than the minimum number of bytes. Here, “n” returned will be greater than the “min” bytes if and only if the error is nil. However, the error returned is “EOF” if and only if no bytes are read.
Note: If an EOF takes place after reading fewer bytes than the stated “min” bytes then this method returns ErrUnexpectedEOF error. But, if the stated minimum number of bytes is more than the length of the stated buffer then this method returns ErrShortBuffer error. However, if the stated reader returns an error after reading at least the stated minimum bytes then the error is declined.
Number of bytes in the buffer: 5 Content in buffer: Geeks
Here, the ‘n’ returned i.e, 5 is greater than ‘min’ i.e, 3 as an error is nil.
panic: short buffer goroutine 1 [running]: main.main() /tmp/sandbox041442440/prog.go:29 +0x20f
Here, the buffer stated in the above code has length lesser than the “min” bytes stated so an error is thrown.