What's the best way to paginate over a slice in Go and avoid errors like panic: runtime error: slice bounds out of range
For example, if I have a slice like
slice := []int{1, 2, 3, 4, 5, 6, 7}
and I call
slice[6:10]
I get a panic error.
I came up with this:
func paginate(x []int, skip int, size int) []int {
limit := func() int {
if skip+size > len(x) {
return len(x)
} else {
return skip + size
}
}
start := func() int {
if skip > len(x) {
return len(x)
} else {
return skip
}
}
return x[start():limit()]
}
Are there better ways to do this in Go?
Thanks