duanliang8464
2017-07-25 03:36
浏览 524
已采纳

如何在GO中将二维数组转换为一维数组?

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"

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douying7289 2017-07-25 09:22
    已采纳

    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.

    已采纳该答案
    打赏 评论
  • duanniu4106 2017-07-25 04:07

    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.

    打赏 评论

相关推荐 更多相似问题