3 回答
TA贡献1809条经验 获得超8个赞
您不需要制作新切片,只需将切片附加logs到divided切片即可。
http://play.golang.org/p/vyihJZlDVy
var divided [][]string
chunkSize := (len(logs) + numCPU - 1) / numCPU
for i := 0; i < len(logs); i += chunkSize {
end := i + chunkSize
if end > len(logs) {
end = len(logs)
}
divided = append(divided, logs[i:end])
}
fmt.Printf("%#v\n", divided)
TA贡献1859条经验 获得超6个赞
另一种变体。它的工作速度比JimB提出的快 2.5 倍。测试和基准测试在这里。
https://play.golang.org/p/WoXHqGjozMI
func chunks(xs []string, chunkSize int) [][]string {
if len(xs) == 0 {
return nil
}
divided := make([][]string, (len(xs)+chunkSize-1)/chunkSize)
prev := 0
i := 0
till := len(xs) - chunkSize
for prev < till {
next := prev + chunkSize
divided[i] = xs[prev:next]
prev = next
i++
}
divided[i] = xs[prev:]
return divided
}
TA贡献1818条经验 获得超3个赞
对任何 []T 使用反射
https://github.com/kirito41dd/xslice
package main
import (
"fmt"
"github.com/kirito41dd/xslice"
)
func main() {
s := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
i := xslice.SplitToChunks(s, 3)
ss := i.([][]int)
fmt.Println(ss) // [[0 1 2] [3 4 5] [6 7 8] [9]]
}
https://github.com/kirito41dd/xslice/blob/e50d91fa75241a3a03d262ad51c8e4cb2ea4b995/split.go#L12
func SplitToChunks(slice interface{}, chunkSize int) interface{} {
sliceType := reflect.TypeOf(slice)
sliceVal := reflect.ValueOf(slice)
length := sliceVal.Len()
if sliceType.Kind() != reflect.Slice {
panic("parameter must be []T")
}
n := 0
if length%chunkSize > 0 {
n = 1
}
SST := reflect.MakeSlice(reflect.SliceOf(sliceType), 0, length/chunkSize+n)
st, ed := 0, 0
for st < length {
ed = st + chunkSize
if ed > length {
ed = length
}
SST = reflect.Append(SST, sliceVal.Slice(st, ed))
st = ed
}
return SST.Interface()
}
- 3 回答
- 0 关注
- 193 浏览
添加回答
举报