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
+5.4k Javascript : How to refresh page with JQuery ?
+18k Golang : Get path name to current directory or folder
+18.3k Golang : Iterating Elements Over A List
+40.7k Golang : How to count duplicate items in slice/array?
+13.5k Golang : Convert spaces to tabs and back to spaces example
+25k Golang : Get current file path of a file or executable
+18.8k Golang : Clearing slice
+6.3k Golang : Map within a map example
+22.3k Golang : Set and Get HTTP request headers example
+34.7k Golang : Upload and download file to/from AWS S3
+19.7k Golang : Determine if directory is empty with os.File.Readdir() function
+9.1k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases