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
+4.1k Golang : Display packages names during compilation
+7k Golang : Get final or effective URL with Request.URL example
+4.9k Golang : How to search a list of records or data structures
+9.3k Golang : Allow Cross-Origin Resource Sharing request
+11.6k Golang : Transform comma separated string to slice example
+4.5k Javascript : Shuffle or randomize array example
+26.8k Golang : Connect to database (MySQL/MariaDB) server
+7.6k Golang : Combine slices but preserve order example
+7.4k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+3.9k Golang : Get a list of crosses(instruments) available to trade from Oanda account
+29.2k Golang : How to redirect to new page with net/http?
+5.8k Golang : Fixing Gorilla mux http.FileServer() 404 problem