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
Create and Print Multi Dimensional Slice in Golang
Print index and element or data from Array, Slice and Map
URL parser in Golang
Split URL and Get Parameters from URL
Convert Int data type to Int16 Int32 Int64
Data encryption with AES-GCM
How to read current directory using Readdir?
Functions mess (recursive anonymous function) in Golang
The return values of a function can be named in Golang
How to find out element position in slice?