Golang : How to iterate a slice without using for loop?
A very simple example on how to iterate a slice of integers without using a for
loop and use recursive method instead.
package main
import (
"fmt"
)
func main() {
integerSlice := []int{0, 1, 2, 3, 4}
loopIntegerSlice(integerSlice, 0)
}
func loopIntegerSlice(numbers []int, index int) int {
// iterate a slice and print out the elements without using a for loop
if index == len(numbers) {
return numbers[index-1] // break here
} else {
n := numbers[index]
fmt.Println(n)
return loopIntegerSlice(numbers, index+1) // use recursive method
}
}
Output:
0
1
2
3
4
See also : Golang : Find the length of big.Int variable example
By Adam Ng(黃武俊)
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+41.5k Golang : How do I convert int to uint8?
+4.5k Linux : sudo yum updates not working
+5.5k Unix/Linux : How to find out the hard disk size?
+4.9k Golang : micron to centimeter example
+11k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+29.7k Golang : Get and Set User-Agent examples
+8.4k Android Studio : Import third-party library or package into Gradle Scripts
+12k Golang : md5 hash of a string
+12.2k Golang : 2 dimensional array example
+22.2k Golang : Read directory content with filepath.Walk()
+16.9k Golang : Get number of CPU cores