Standard library / compress/gzip

compress/gzip.Reader.Read()

Decompress into the supplied buffer. Returned bytes may accompany an error; checksum validation is only complete after reading to EOF. Expected stdout: 'Go\n'.

Formal Syntax & Structure

go syntaxgo
func (z *Reader) Read(p []byte) (n int, err error)

Parameters & Attributes

NameTypeDescription
p[]byteDestination for decompressed bytes; process returned bytes before handling errors.

Return Value

(n int, err error)

Number of bytes processed and error; check both.

Working Example

Example Snippetgo
package main
import (  "bytes"  "compress/gzip"  "fmt"  "io")
func must(e error) {  if e != nil {    panic(e)  }}func pack(s string) []byte {  var b bytes.Buffer  w := gzip.NewWriter(&b)  _, e := w.Write([]byte(s))  must(e)  must(w.Close())  return b.Bytes()}func unpack(b []byte) string {  r, e := gzip.NewReader(bytes.NewReader(b))  must(e)  p, e := io.ReadAll(r)  must(e)  must(r.Close())  return string(p)}func main() {  r, e := gzip.NewReader(bytes.NewReader(pack("Go")))  must(e)  p := make([]byte, 1)  n, e := r.Read(p)  must(e)  fmt.Print(string(p[:n]))  rest, e := io.ReadAll(r)  must(e)  must(r.Close())  fmt.Println(string(rest))}
Go Reference