Go进行多个切片的拼接

作者:guoxj
浏览:373

普通的解决方式

package main

import "fmt"

func main() {
    slice1 := []string{"apple", "banana", "peach" }
    slice2 := []string{"avacado", "kiwi", "pineapple"}

    slice3 := append(slice1, slice2...)
    fmt.Println(slice3)
}

多于两个,那简单封装下上面的逻辑

package main

import "fmt"

func main() {

 slices := [][]string{{"apple", "banana", "peach"},
  {"orange", "grape", "mango"},
  {"strawberry", "blueberry", "raspberry"}}

 fmt.Println(concatAppend(slices))

}
func concatAppend(slices [][]string) []string {
 var tmp []string
 for _, s := range slices {
  tmp = append(tmp, s...)
 }
 return tmp
}

更高效的选择————一次分配足够内存,避免过多的底层数组扩容影响效率

package main

import "fmt"

func main() {

 slices := [][]string{{"apple", "banana", "peach"},
  {"orange", "grape", "mango"},
  {"strawberry", "blueberry", "raspberry"}}

 fmt.Println(concatCopyPreAllocate(slices))

}

func concatCopyPreAllocate(slices [][]string) []string {
 var totalLen int
 for _, s := range slices {
  totalLen += len(s)
 }
 tmp := make([]string, totalLen)
 var i int
 for _, s := range slices {
  i += copy(tmp[i:], s)
 }
 return tmp
}

 




登录后回复

共有0条评论