如何存储字节切片的切片?

huangapple go评论81阅读模式
英文:

how to store a slice of byte slices?

问题

我想了解如何将多个字节切片分别存储在一个切片中。如下所示,我希望存储结构体能够存储在buf中找到的n的压缩结果。

type storage struct {
    compressed [][]byte
}

func (s *storage) compress(n []byte) {
    var buf bytes.Buffer
    w := gzip.NewWriter(&buf)
    w.Write(n)
    w.Close()
    store := buf.Bytes()
    s.compressed = append(s.compressed, store)
}

在上面的代码中,compressed字段被定义为一个二维字节切片,用于存储多个压缩结果。compress方法将给定的字节切片 n 进行压缩,并将压缩结果存储在 s.compressed 中。每次调用 compress 方法时,压缩结果都会被追加到 s.compressed 中。

英文:

I would like to understand how to store several byte slices separately in a slice. As hopefully illustrated below, I want the storage struct to store the result of the compressed result of n found in buf.

type storage struct 
{
	compressed []byte 
}		

func (s* storage) compress(n []byte) {
	  var buf bytes.Buffer
	  w := gzip.NewWriter(&buf)
	  w.Write(n)
	  w.Close()
	  store := buf.Bytes()
	  s.compressed = append(s.compressed, store)
}

答案1

得分: 6

在你的代码中,compressed 是一个字节切片。如果你想要存储字节切片的切片,你需要一个字节切片的切片。所以将 compressed 的类型改为 [][]byte

英文:

In your code compressed is a slice of bytes. If you want to store slices of bytes you need a slice of slices of bytes. So change the type of compressed to [][]byte

huangapple
  • 本文由 发表于 2013年10月6日 00:44:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/19200175.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定