Iterate over Elements of Slice using For Loop
To iterate over elements of a slice using for loop, use for loop with initialization of (index = 0), condition of (index < slice length) and update of (index++). Inside for loop access the element using slice[index].
The syntax to iterate over slice x
using for loop is
</>
Copy
for i := 0; i < len(x); i++ {
//x[i]
}
Examples
Iterate over Elements of Slice
In the following program, we take a slice x
of size 5
. We iterate over the elements of this slice using for loop.
example.go
</>
Copy
package main
import (
"fmt"
)
func main() {
var x = []int{10, 20, 30, 40, 50}
for i := 0; i < len(x); i++ {
fmt.Println(x[i])
}
}
Output
10
20
30
40
50
Iterate over Elements of String Slice
Now, let us take a slice of strings, and iterate over these string elements.
example.go
</>
Copy
package main
import (
"fmt"
)
func main() {
var x = []string{"apple", "banana", "cherry"}
for i := 0; i < len(x); i++ {
fmt.Println(x[i])
}
}
Output
apple
banana
cherry
Conclusion
In this Golang Tutorial, we learned how to iterate over elements of a slice using for loop in Go programming, with the help of example programs.