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
+5k Facebook : How to place save to Facebook button on your website
+6.2k PHP : How to check if an array is empty ?
+5.8k Fix fatal error: evacuation not done in time problem
+7.8k Javascript : Push notifications to browser with Push.js
+12.8k Golang : Exit, terminating or aborting a program
+13k Golang : Convert int(year) to time.Time type
+30.3k Golang : Get time.Duration in year, month, week or day
+15.5k Golang : Get query string value on a POST request
+5.3k Golang : Issue HTTP commands to server and port example
+7.3k Golang : Gorrila mux.Vars() function example
+14.9k Golang : Normalize unicode strings for comparison purpose
+10.8k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)