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
+7.2k Golang : How to handle file size larger than available memory panic issue
+8.6k Golang : Sort lines of text example
+21.8k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+9.1k Golang : Find the length of big.Int variable example
+9.9k Golang : How to tokenize source code with text/scanner package?
+5.9k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+9.2k Golang : Extract or copy items from map based on value
+6.9k Golang : Null and nil value
+7.2k Golang : Gorrila set route name and get the current route name
+5.2k Gogland : Datasource explorer
+9.8k Golang : Get login name from environment and prompt for password
+8.8k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)