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