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
+20.4k error: trying to remove "yum", which is protected
+7.3k Golang : Loop each day of the current month example
+5.3k Golang : Populate or initialize struct with values example
+6.9k Golang : How to determine if a year is leap year?
+6.5k Golang : Sort and reverse sort a slice of bytes
+11k Golang : Simple client server example
+14.1k Golang : Check if a directory exist or not
+4.7k Setting $GOPATH environment variable for Unix/Linux and Windows
+6.4k Golang : Get current time from the Internet time server(ntp) example
+3.7k Golang : Shuffle strings array
+13.4k Golang : How to count the number of repeated characters in a string?