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
+12.2k Golang : How to display image file or expose CSS, JS files from localhost?
+6.2k Golang : Test input string for unicode example
+20.9k Golang : For loop continue,break and range
+14.3k Golang : How to filter a map's elements for faster lookup
+6k Golang : Debug with Godebug
+7.2k Golang : Not able to grep log.Println() output
+9.6k Random number generation with crypto/rand in Go
+16.3k Golang : Test floating point numbers not-a-number and infinite example
+13.5k Golang : Query string with space symbol %20 in between
+11.6k Golang : Calculations using complex numbers example
+11.8k Golang : Convert decimal number(integer) to IPv4 address