Reputation: 399
How do I iterate through a Go slice 4 items at a time.
lets say I have [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
I want a for loop to be able to get
[1,2,3,4] //First Iteration
[5,6,7,8] //Second Iteration
[9,10,11,12] //Third Iteration
[13,14,15,] // Fourth Iteration
I can do this in java and python but for golang I really dont have an idea.
Upvotes: 3
Views: 2317
Reputation: 166529
How To Iterate on Slices in Go, Iterating 4 items at a time. I want a for loop.
In Go, readability is paramount. First we read the normal path, then we read the exception/error paths.
We write the normal path.
n := 4
for i := 0; i < len(s); i += n {
ss := s[i : i+n]
fmt.Println(ss)
}
We use n
for the stride value throughout.
We write a little tweak that doesn't disturb the normal path to handle an exception, the end of the slice.
if n > len(s)-i {
n = len(s) - i
}
For example,
package main
import "fmt"
func main() {
s := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
n := 4
for i := 0; i < len(s); i += n {
if n > len(s)-i {
n = len(s) - i
}
ss := s[i : i+n]
fmt.Println(ss)
}
}
Playground: https://play.golang.org/p/Vtpig2EeXB7
Output:
[1 2 3 4]
[5 6 7 8]
[9 10 11 12]
[13 14 15]
Upvotes: 3
Reputation: 934
For example,
package main
import "fmt"
func main() {
slice := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
for i := 0; i < len(slice); i += 4 {
var section []int
if i > len(slice)-4 {
section = slice[i:]
} else {
section = slice[i : i+4]
}
fmt.Println(section)
}
}
Playground: https://play.golang.org/p/kf7_OJcP13t
Output:
[1 2 3 4]
[5 6 7 8]
[9 10 11 12]
[13 14 15]
Upvotes: 3