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
Example: How to use TeeReader from IO Package in Golang?
How do you create an HTTP client in Go?
How do you handle HTTP errors in Go?
Golang panic recover example
Explain in Brief Golang error handling best practices
This sample program demonstrates how to create multiple goroutines and how the goroutine scheduler behaves with three logical processors.
Program in Go language to print Pascal's Triangle
How to write backslash in Golang string?
Exploring Blockchain: Top 15 Real-World Use Cases in 2024
How do you create an HTTP server in Go?