1

Here are two data structures

result []byte
chunk  [][]byte

"chunk" is initialized as follows

chunk := make([][]byte, 3)
for i := 0 ; i < 5; i++ {
      chunk[i] = data //data is a byte array
}

How can I concatenate chunks into to result[]?

Example

If chunks is "123", "456", "789", then result should be "123456789"

yazgazan
  • 368
  • 1
  • 10
Qi Zhang
  • 631
  • 1
  • 7
  • 15

2 Answers2

4

Simple.

l := 0
for _, v := range chunks {
    l += len(v)
}
result := make([]byte, 0, l)
for _, v := range chunks {
    result = append(result, v...)
}

The first loop adds up all the lengths, the new slice is allocated, and then another loop is used to copy the old slices into the new one.

While there is a simpler way to handle this particular case using functions from the bytes package, this solution will work with slices of any type.

Milo Christiansen
  • 3,204
  • 2
  • 23
  • 36
  • No need to do this manually, the `"bytes".Join` function from the standard library is perfect for the job. – yazgazan Jul 25 '17 at 09:24
  • True enough. Generally when I am doing things like this it is part of something larger or the type isn't `byte`, so the handy helpers aren't useful... So I kinda forgot it existed... I'll edit my answer to point out this is s generic solution. – Milo Christiansen Jul 25 '17 at 12:45
3

You can use the "bytes".Join function from the standard library:

result := bytes.Join(chunks, nil)

First argument is your slice of slices ([][]byte), second argument is the separator (aka glue). In your case, the separator is an empty slice of bytes (nil works as well).

In the playground: https://play.golang.org/p/8pquRk7PDo.

yazgazan
  • 368
  • 1
  • 10