Example: How to use ReadFull from IO Package in Golang?
ReadFull reads exactly len(buf) bytes from r into buf. It returns the number of bytes copied and an error if fewer bytes were read. Use ReadFull if you want to read an exact number of bytes from something.
Example
package main
import (
"io"
"fmt"
"strings"
)
type Example struct {
ReaderLength int
TextStr string
}
func main() {
examples := []Example{
{10, "Go is a programming language created at Google in 2007."},
{10, "Golang"},
{10, "Robert Griesemer"},
{10, "Jobs, Code, Videos and News for Go hackers."},
}
for _, ex := range examples {
read := strings.NewReader(ex.TextStr)
buffer := make([]byte, ex.ReaderLength)
bytesRead, err := io.ReadFull(read, buffer)
fmt.Printf("\nLen(buffer)=%d, BytesRead=%d, Error=%v, (%s)\n",ex.ReaderLength, bytesRead, err, ex.TextStr)
}
}
Output
Len(buffer)=10, BytesRead=10, Error=, (Go is a programming language created at Google in 2007.)
Len(buffer)=10, BytesRead=6, Error=unexpected EOF, (Golang)
Len(buffer)=10, BytesRead=10, Error=, (Robert Griesemer)
Len(buffer)=10, BytesRead=10, Error=, (Jobs, Code, Videos and News for Go hackers.)
Most Helpful This Week
Creating a Struct Instance Using a Struct Literal
Golang program for implementation of Selection Sort
Golang program for implementation of Interpolation Search
Make Your Retirement Luxurious with These 5 Game-Changing Altcoins
GO Program to Calculate Sum of Natural Numbers Using for.....Loop
Empowering Developers: Google Cloud’s Generative AI Systems