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.8k Golang : Sort and reverse sort a slice of bytes
+4.8k PHP : Extract part of a string starting from the middle
+6k Golang : Detect variable or constant type
+14k Golang : Gin framework accept query string by post request example
+15.3k Golang : Save(pipe) HTTP response into a file
+12.3k Golang : Split strings into command line arguments
+12.9k Golang : Listen and Serve on sub domain example
+11.3k Golang : Simple image viewer with Go-GTK
+7.3k Golang : Use modern ciphers only in secure connection
+11.6k Use systeminfo to find out installed Windows Hotfix(s) or updates
+7.5k Golang : Word limiter example
+22.8k Generate checksum for a file in Go