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
+14.8k Golang : Generate universally unique identifier(UUID) example
+24.9k Golang : Convert(cast) string to uint8 type and back to string
+29.4k Golang : How to convert(cast) string to IP address?
+13.2k Golang : Find network of an IP address
+17.5k Golang : Set, Get and List environment variables
+12.2k Golang : Generate Code128 barcode
+12.1k Golang : Linear algebra and matrix calculation example
+31.5k Golang : Smarter Error Handling with strings.Contains()
+21.8k Golang : Gorilla mux routing example
+12.9k Golang : Check if a file exist or not
+3.8k Linux : sudo yum updates not working
+14.9k Golang : Get sub string example