Standard library / compress/zlib

compress/zlib.Writer.Reset()

Discard current compressor state and reuse allocations with a new destination, keeping compression settings. Close the previous stream first if it must remain valid. Expected stdout: 'Go next\n'.

Formal Syntax & Structure

go syntaxgo
func (z *Writer) Reset(w io.Writer)

Parameters & Attributes

NameTypeDescription
wio.WriterDestination for compressed bytes; closing the compressor does not close this writer.

Working Example

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