Standard library / compress/lzw

compress/lzw.Reader.Read()

Read decompressed bytes into a destination slice. Handle bytes before errors and do not assume one Read fills the buffer. Expected stdout: 'Go\n'.

Formal Syntax & Structure

go syntaxgo
func (r *Reader) Read(b []byte) (int, error)

Parameters & Attributes

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

Return Value

(int, error)

Number of bytes processed and error; check both.

Working Example

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