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.
Example
package main
import (
"io"
"fmt"
"strings"
)
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)
}
}
Output
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
Convert Float32 to Float64 and Float64 to Float32
This sample program demonstrates how to create multiple goroutines and how the goroutine scheduler behaves with three logical processors.
How do you handle HTTP requests in Go?
How to remove special characters from a string in GoLang?
GO language program with example of Array Reverse Sort Functions for integer and strings
Illustration of Checkpoint Synchronization in Golang
Go program to find Name Server (NS) record of a domain
How to initialize a struct containing a slice of structs in Golang?
Golang read csv file into struct
Golang program for implementation of Shell Sort