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
+13k Golang : Get constant name from value
+12.2k Golang : Listen and Serve on sub domain example
+12.1k Golang : "https://" not allowed in import path
+12.2k Golang : zlib compress file example
+9.2k Golang : Detect number of active displays and the display's resolution
+12k Elastic Search : Return all records (higher than default 10)
+28.8k Golang : JQuery AJAX post data to server and send data back to client example
+10.1k Golang : Allow Cross-Origin Resource Sharing request
+33.1k Golang : How to check if slice or array is empty?
+23.1k Golang : Check if element exist in map
+18.6k Golang : Get host name or domain name from IP address
+22.5k Golang : Gorilla mux routing example