如何将[][]byte转换为[]byte?

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

How do I convert [][]byte to []byte?

问题

我有一个函数,它将数据分割并返回子切片的切片:

func split(buf []byte, lim int) [][]byte

显然,如果我这样做:

n, err = out.Write(split(buf[:n], 100))

我会得到一个错误:

无法将split(buf[:n], 100)(类型为[][]byte)转换为类型[]byte

如何将[][]byte转换为[]byte

基于@Wishwa Perera的编辑:https://play.golang.org/p/nApPAYRV4ZW

英文:

I have a function which splits data and returns slice of subslices:

(buf []byte, lim int) [][]byte

Obviously I get an error if I do:

n, err = out.Write(split(buf[:n], 100))

The error:

> cannot convert split(buf[:n], 100) (type [][]byte) to type []byte

How do I convert [][]byte to []byte?

Edit based on @Wishwa Perera: https://play.golang.org/p/nApPAYRV4ZW

答案1

得分: 1

由于您将buf拆分为chunks,您可以通过循环遍历split的结果,将它们逐个传递给Write

for _, chunk := range split(buf[:n], 100) {
	if _, err := out.Write(chunk); err != nil {
		panic(err)
	}
}
英文:

Since you are splitting buf into chunks, you can pass them individually to Write by looping over the result of split.

for _, chunk := range split(buf[:n], 100) {
	if _, err := out.Write(chunk); err != nil {
		panic(err)
	}
}

答案2

得分: 1

如果out是一个net.Conn,就像你在另一个问题中提到的那样,那么可以使用net.Buffers来写入[][]byte

b := net.Buffers(split(buf[:n], 100))
_, err := b.WriteTo(out)
if err != nil {
   panic(err)
}
英文:

If out is a net.Conn as in your other question, then use net.Buffers to write the [][]byte.

b := net.Buffers(split(buf[:n], 100))
_, err := b.WriteTo(out)
if err != nil {
   panic(err)
}

huangapple
  • 本文由 发表于 2021年7月27日 16:21:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/68541302.html
匿名

发表评论

匿名网友

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

确定