Example: How to use ReadAtLeast from IO Package in Golang?

ReadAtLeast reads from r into buf until it has read at least min bytes. It returns specific errors to signal specific cases when the minimum couldn’t be read due to EOF.


package main

import (

type Example struct {
	ReaderLength int
	Minimum  int
	TextStr  string

func main() {
	examples := []Example{
		{10, 5, "Go is a programming language created at Google in 2007."},
		{10, 10, "Golang"},
		{10, 00, "Robert Griesemer"},
		{10, 15, "Jobs, Code, Videos and News for Go hackers."},
	for _, ex := range examples {
		rd := strings.NewReader(ex.TextStr)
		buffer := make([]byte, ex.ReaderLength)
		bytesRead, err := io.ReadAtLeast(rd, buffer, ex.Minimum)
		fmt.Printf("\nLen(buffer)=%d, Min=%d, BytesRead=%d, Error=%v, (%s)\n",ex.ReaderLength, ex.Minimum, bytesRead, err, ex.TextStr)


Len(buffer)=10, Min=5, BytesRead=10, Error=, (Go is a programming language created at Google in 2007.)

Len(buffer)=10, Min=10, BytesRead=6, Error=unexpected EOF, (Golang)

Len(buffer)=10, Min=0, BytesRead=0, Error=, (Robert Griesemer)

Len(buffer)=10, Min=15, BytesRead=0, Error=short buffer, (Jobs, Code, Videos and News for Go hackers.)
Most Helpful This Week