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
+5.6k Golang : Totalize or add-up an array or slice example
+11.4k Golang : Exit, terminating or aborting a program
+8.6k Golang : Validate IPv6 example
+6.6k Gogland : Single File versus Go Application Run Configurations
+5.9k Golang : Calculate BMI and risk category
+11.6k Golang : Convert int(year) to time.Time type
+10.6k Golang : Convert decimal number(integer) to IPv4 address
+17.9k Golang : Get current URL example
+4.4k PHP : Hide PHP version information from curl
+16.5k Golang : Put UTF8 text on OpenCV video capture image frame
+14.3k Golang : invalid character ',' looking for beginning of value
+10.5k How to tell if a binary(executable) file or web application is built with Golang?