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
+6.9k Golang : Muxing with Martini example
+23.2k Golang : simulate tail -f or read last line from log file example
+17.7k Golang : Upload/Receive file progress indicator
+18.8k Golang : Iterating Elements Over A List
+6.5k PHP : Proper way to get UTF-8 character or string length
+23.3k Golang : Print out struct values in string format
+46.7k Golang : Marshal and unmarshal json.RawMessage struct example
+20.4k Golang : How to get own program name during runtime ?
+5.7k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)
+8.5k Golang : Ackermann function example
+12.7k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+24.1k Golang : Call function from another package