doushi5024 2013-01-31 09:31
浏览 46
已采纳

如何使用golang的zlib?

var buf bytes.Buffer

var outputBuffer [100]byte
b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"],"test":{"prop1":1,"prop2":[1,2,3]}}`)

w := zlib.NewWriter(&buf)
r, _ := zlib.NewReader(&buf)
w.Write(b)
w.Flush()
r.Read(outputBuffer)//cannot use outputBuffer (type [100]byte) as type []byte in function argument
fmt.Println(outputBuffer)

what can I do to make this right? thanks

  • 写回答

2条回答 默认 最新

  • drnmslpz42661 2013-01-31 15:36
    关注

    well you tried to use an array as a slice. It expected a []byte and you gave it a [100]byte. A []byte has a dynamic width, while a [100]byte is always 100 bytes. An array's size is a part of its type; a [1]int is a different type from a [2]int. That's why almost everything operates on slices.

    But that's not the only thing. When you call Read on an io.Reader directly, it fills in the target slice up to its current width, without expanding it. If you had made your output slice 10 bytes wide (make([]byte, 10)), the output you would see would be {"Name":"W.

    var in bytes.Buffer
    b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"],"test":{"prop1":1,"prop2":[1,2,3]}}`)
    w := zlib.NewWriter(&in)
    w.Write(b)
    w.Close()
    
    var out bytes.Buffer
    r, _ := zlib.NewReader(&in)
    io.Copy(&out, r)
    os.Stdout.Write(out.Bytes())
    

    but at this point, you might as well just pass os.Stdout into io.Copy, just like they do in the standard library docs. The only difference is we have kept a copy of the output format, but... what if the output is so large that you don't want to hold it in memory? That's why io.Copy takes an interface: you can take compressed data, and write an uncompressed version of it directly to any output stream, including stdout but also including things like files, unix sockets, or network sockets.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度