func main() {
source := []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"}
pagesize := 10
pagesizee := 4
fmt.Printf("%+v\n", splitArray(source, IntToInt64(splitArrayCnt(len(source), pagesize)), int64(pagesize)))
// 输出:[[1 2 3 4 5 6 7 8 9 10] [11 12]]
fmt.Printf("%+v\n", splitArray(source, IntToInt64(splitArrayCnt(len(source), pagesizee)), int64(pagesizee)))
// 输出:[[1 2 3 4] [5 6 7 8] [9 10 11 12]]
}
// sources源数组,num拆分份数,size每份的大小
func splitArray(sources []string, num, pagesize int64) [][]string {
max := int64(len(sources))
if max < num {
return nil
}
var segmens = make([][]string, 0)
quantity := pagesize
end := int64(0)
for i := int64(1); i <= num; i++ {
qu := i * quantity
if i != num {
segmens = append(segmens, sources[i-1+end:qu])
} else {
segmens = append(segmens, sources[i-1+end:])
}
end = qu - i
}
return segmens
}
// sourceslen源数组长度,pagesize页数据量
// 获取拆分份数
func splitArrayCnt(sourceslen, pagesize int) int {
if sourceslen < pagesize {
return 1
}
s := sourceslen / pagesize
y := sourceslen % pagesize
if y > 0 {
return s + 1
} else {
return s
}
}
//IntToInt64 int 转int64
func IntToInt64(i int) int64 {
i64, _ := strconv.ParseInt(strconv.Itoa(i), 10, 64)
return i64
}
注:源数组类型可以换成自己需要的类型
参考自:https://blog.csdn.net/weixin_43058470/article/details/104052969 做了一点点更改