标签:10 分页 pageSize fmt len Golang source int64 数组
背景:线上的接口处bug,测试很着急的找到我。当然,这个bug 并不是我写出来的,而是经历过日积月累,之前的开发人员,也没有关注过这个问题,出现在类似bug 也是在所难免的。
话不多说,这个问题刚好需要数组的分页可以搞定。代码如下:
package main import ( "fmt" "strconv" ) func main() { source := []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21} 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]] res := splitArray(source, IntToInt64(splitArrayCnt(len(source), pageSize)), int64(pageSize)) fmt.Println(len(res)) for _, re := range res { fmt.Println(re) } } // sources源数组,num拆分份数,size每份的大小 func splitArray(sources []int64, num, pageSize int64) [][]int64 { max := int64(len(sources)) if max < num { return nil } var segmens = make([][]int64, 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 }
标签:10,分页,pageSize,fmt,len,Golang,source,int64,数组 来源: https://www.cnblogs.com/taotaozhuanyong/p/15498261.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。