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"
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.
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.