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
+20.6k Golang : Saving private and public key to files
+7.5k Golang : Convert(cast) io.Reader type to string
+13k Golang : How to get a user home directory path?
+13k Golang : Handle or parse date string with Z suffix(RFC3339) example
+9.5k Javascript : Read/parse JSON data from HTTP response
+32.9k Delete a directory in Go
+9.3k Golang : Terminate-stay-resident or daemonize your program?
+5.3k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+5.8k Golang : Extract unicode string from another unicode string example
+39.4k Golang : Remove dashes(or any character) from string
+7.7k Golang : Reverse a string with unicode
+9.2k Golang : Temperatures conversion example